Instance, Class, & Static Methods
In Python, a method is simply a function that belongs to a class. However, not all methods are created equal. Depending on whether the method needs to access the instance, the class itself, or neither, you must choose the correct decorator.
1. Instance Methods
Section titled “1. Instance Methods”The most common type of method. They take self as the first argument.
- Access: Can read and modify instance attributes (
self.x) and class attributes (self.__class__.y). - Purpose: To implement the specific behavior of an object.
class Player: def __init__(self, name): self.name = name self.health = 100
def take_damage(self, amount): self.health -= amount2. Class Methods (@classmethod)
Section titled “2. Class Methods (@classmethod)”Class methods take cls (the class itself) as the first argument instead of self.
- Access: Can modify the class state that applies across all instances.
- Primary Use Case: Factory Methods. These are methods that provide alternative ways to create an object.
import json
class User: def __init__(self, username, email): self.username = username self.email = email
@classmethod def from_json(cls, json_data): """Create a User instance from a JSON string.""" data = json.loads(json_data) return cls(username=data['user'], email=data['email'])
# Usageraw = '{"user": "alice_99", "email": "a@b.com"}'user = User.from_json(raw)3. Static Methods (@staticmethod)
Section titled “3. Static Methods (@staticmethod)”Static methods don’t take self or cls. They are essentially just normal functions that live inside the class namespace.
- Access: Cannot access instance or class attributes.
- Purpose: For utility logic that is related to the class but doesn’t need to know anything about a specific instance.
class Validator: @staticmethod def is_valid_email(email): return "@" in email and "." in email
# UsageValidator.is_valid_email("test@example.com")4. Under the Hood: Bound vs. Unbound Methods
Section titled “4. Under the Hood: Bound vs. Unbound Methods”How does Python know to pass self?
When you access a method through an instance (my_obj.my_method), Python creates a Bound Method. This is a special object that combines the function with the instance. When you call it, it automatically “injects” the instance as the first argument.
If you access it through the class (MyClass.my_method), it is an Unbound Method (just a regular function).
5. Summary Table: Which one to use?
Section titled “5. Summary Table: Which one to use?”| Method Type | Decorator | First Arg | Usage |
|---|---|---|---|
| Instance | None | self | Most of the time. Modifying object state. |
| Class | @classmethod | cls | Factory methods. Modifying class state. |
| Static | @staticmethod | None | Utility logic. No access to state. |