A class function in Python is a function defined inside a class that operates on instances of that class or the class itself. It's bound to the class and automatically receives the instance (self) or the class (cls) as its first argument.
When you define a function inside a class, it becomes a method. This method can access and modify instance attributes, call other methods, or perform actions specific to the object's state. The first parameter-typically named self-refers to the individual instance being used.
For example, defining a greet() method inside a Person class allows each person object to say hello:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, I'm {self.name}"
alice = Person("Alice")
print(alice.greet()) # Output: Hello, I'm Alice
Without the self parameter, the method wouldn't know which instance's data to use. This binding helps each object maintains its own state while sharing common behavior.
Python uses a descriptor protocol to bind functions to instances. When you access a method through an instance-like alice.greet()-Python automatically wraps the function and passes the instance as the first argument.
This process happens behind the scenes. You don't need to manually pass self when calling the method. But if you reference the method directly-Person.greet-you must pass an instance explicitly:
Person.greet(alice) # Correct: manually pass the instance
# alice.greet() # Also correct: automatic binding
Understanding this mechanism prevents confusion when debugging method calls or passing methods as arguments.
There are three main kinds of class functions: instance methods, class methods, and static methods. Each serves a different purpose and uses a different decorator.
| Type | Decorator | First Parameter | Use Case |
|---|---|---|---|
| Instance method | None | self |
Access or modify instance-specific data |
| Class method | @classmethod | cls |
Work with class-level data or create alternative constructors |
| Static method | @staticmethod | None | Group utility functions related to the class but not dependent on class or instance state |
Instance methods are the most common. They're called on objects and have access to self. Class methods are useful for factory patterns-for example, creating a Person from a string like "John-Doe".
Static methods behave like regular functions but live inside the class namespace. They don't receive self or cls and are often used for helper logic. For example, a validate_email() function inside a User class keeps related functionality together.
Many beginners assume that a function inside a class is automatically available to all instances. That's true-but only if it's properly defined with self. A missing self causes a TypeError when the method is called.
Another mistake is thinking that class functions can't be reused outside the class. While they're defined within the class, they can be assigned to variables or passed around just like any other callable:
def introduce(person):
return person.greet()
person = Person("Bob")
say_hello = person.greet
print(say_hello()) # Output: Hello, I'm Bob
This shows that class functions are first-class objects in Python-they can be treated like any other function.
Some developers confuse class functions with global functions. A global function is independent of any class. A class function belongs to a class and has access to its data. The key difference lies in context and binding.
Consider a banking application. A BankAccount class might include methods like deposit(), withdraw(), and get_balance(). These are all class functions because they act on the account's balance and depend on the instance.
Suppose you want to create an account from a JSON string. A class method makes this clean:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
@classmethod
def from_json(cls, json_data):
data = json.loads(json_data)
return cls(data["owner"], data["balance"])
account_json = '{"owner": "Jane", "balance": 1000}'
account = BankAccount.from_json(account_json)
print(account.owner) # Output: Jane
This pattern avoids cluttering the __init__ method with parsing logic. It also enables multiple ways to construct the same object.
I once built a configuration loader using class methods. Each config type had a from_file() method that parsed a file and returned a configured instance. This kept setup code organized and reusable across projects.
Not all functions in a class are methods. Functions defined inside a class but not intended to operate on instances are sometimes called "class-level functions." They're not bound to self and aren't automatically invoked on instances.
For example:
class Calculator:
def add(self, a, b):
return a + b
def multiply(a, b): # No self! This is not a method
return a * b
The multiply function above is not a method-it's a regular function stored in the class namespace. It doesn't receive self and cannot access instance attributes. Calling Calculator.multiply(2, 3) works, but calc = Calculator(); calc.multiply(2, 3) fails unless you use staticmethod.
Another subtle point: class functions are resolved at runtime. If you change a method after instantiation, the new version applies to all existing instances. This behavior supports changing modification but can lead to bugs if not understood.
Always use self as the first parameter in instance methods. This is standard practice and required for proper binding. Omitting it results in errors when the method is called on an instance.
Use @classmethod when the method needs access to the class but not to instance data. Use @staticmethod for pure utility functions that don't interact with the class or instance state.
Keep methods focused. A single method should do one thing well. If a method grows too long, split it into smaller ones. This improves readability and testability.
When designing classes, ask: "Does this function need to access instance data?" If yes, make it an instance method. If it only uses parameters, consider making it a static method or moving it outside the class entirely.
Understanding class functions leads naturally to deeper topics like inheritance, method resolution order (MRO), and polymorphism. When a subclass overrides a method, the correct version is called based on the actual object type.
For example, if Student inherits from Person and overrides greet(), calling student.greet() returns the student's version-not the parent's.