Class & Static Methods
Beyond instance methods: @classmethod for alternative constructors and @staticmethod for related helpers.
Most methods you've written are instance methods — they take self and act on one object. Python has two more kinds, marked with decorators: class methods (@classmethod, receive the class as cls) and static methods (@staticmethod, receive nothing special).
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
# instance method — works on one pizza
def describe(self):
return f"Pizza with {', '.join(self.toppings)}"
# class method — an alternative constructor
@classmethod
def margherita(cls):
return cls(["tomato", "mozzarella", "basil"])
# static method — a related helper, no self/cls
@staticmethod
def is_vegetarian(toppings):
return "pepperoni" not in toppings
p = Pizza.margherita()
print(p.describe())
print(Pizza.is_vegetarian(p.toppings))#Class methods = alternative constructors
Because a class method receives cls, it can build and return a new instance — a clean way to offer named constructors like Pizza.margherita(). Using cls (not the literal class name) means subclasses get the right type automatically.
Which one to use?
Instance method — needs the object's data (self). Class method — needs the class but not a specific instance (factories, config). Static method — a plain function that just belongs with the class for organization; it touches neither self nor cls.
What does a @classmethod receive as its first argument?
Key takeaways
- Instance methods take `self` and act on one object.
- `@classmethod` takes `cls` (the class) — great for alternative constructors like `Pizza.margherita()`.
- `@staticmethod` takes no special first argument — a helper grouped with the class.
- Use `cls(...)` in class methods so subclasses build the correct type.
What does this print?
class Temp:
def __init__(self, c):
self.c = c
@classmethod
def freezing(cls):
return cls(0)
print(Temp.freezing().c)This method doesn't use the instance or the class — what should it be?
class MathUtils:
def add(self, a, b):
return a + b
MathUtils.add(2, 3) # TypeError!Complete the decorator that makes `from_dict` receive the class as `cls`.
@ def from_dict(cls, d): return cls(d['x'])
Add a @classmethod called from_string to a Point class that parses "3,4" into Point(3, 4). The class stores self.x and self.y.
Try it live — edit the code and hit Run to execute real Python: