Lesson 28 / 47
Class & Static Methods
Methods that belong to the class itself, not a particular instance.
@classmethod vs @staticmethod
@classmethod receives the class (cls) instead of an instance — often used for alternate constructors. @staticmethod receives neither and is just a function grouped inside the class.
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@staticmethod
def is_valid_topping(name):
return isinstance(name, str) and len(name) > 0
p = Pizza.margherita()
print(p.toppings)
print(Pizza.is_valid_topping("basil"))Quick check: Which decorator lets a method create a new instance without an existing object?
- @staticmethod
- @classmethod
- @property
Answer
@classmethod — @classmethod receives the class itself (cls) and can build and return a new instance.