Junior — Middle
How do static methods differ from dynamic methods in Python, and what are their main features?
sobes.tech AI
Answer from AI
In Python, static and dynamic methods differ in how they are called and in what they receive as the first parameter.
-
Static methods (@staticmethod) do not automatically receive a reference to the object (self) or the class (cls). They behave like regular functions but are located inside the class for logical grouping. They can be called via the class or an instance.
-
Dynamic methods (regular methods) receive a reference to the object (self) as the first parameter. They can work with the state of a specific class instance.
Example:
class MyClass:
@staticmethod
def static_method(x, y):
return x + y
def instance_method(self, x):
return x * 2
obj = MyClass()
print(MyClass.static_method(3, 4)) # 7
print(obj.static_method(5, 6)) # 11
print(obj.instance_method(5)) # 10
Main features:
- Static methods cannot access instance or class attributes unless explicitly passed.
- Dynamic methods can work with the object's state.
Static methods are useful for utility functions related to the class but not dependent on its state.