In Python, there are three main types of methods: instance methods, class methods, and static methods. Historically, Python supported only instance methods (with the first parameter self). Over time, the need for additional types of methods arose: accessible through the class without tying them to an object and with access to the class itself.
Problem: Often, there is a requirement to create methods that do not depend on the state of an object instance (for example, factory methods) or do not need any class context but logically belong in the class structure.
Solution: The decorators @classmethod and @staticmethod are used.
Code example:
class Example: def instance_method(self): return f'instance: {self}' @classmethod def class_method(cls): return f'class: {cls}' @staticmethod def static_method(): return 'static'
Key features:
Can a static method access class and instance attributes?
No, a static method does not receive a reference to either the class or the object.
class A: x = 10 @staticmethod def f(): # print(self.x) # Error pass
Can class methods be overridden in subclasses?
Yes, when calling a classmethod through a subclass, the actual class will always be the first argument, not the parent class.
class Base: @classmethod def name(cls): return cls.__name__ class Child(Base): pass Child.name() # "Child"
Why can't you use self for class methods?
Because a class method is not bound to a specific object, but rather to the class as a whole; self is not accessible without creating an instance.
A factory method was defined as a staticmethod, and inside it attempts to create an instance of the class through self, which leads to errors or code duplication.
Pros:
Cons:
The factory is declared through classmethod, and inside it uses the actual class (cls) to create an instance. Inheritors are correctly created through this factory.
Pros:
Cons: