Today, someone asked me about static methods and said is that right that static method can't access or modify a class state?
Today, someone asked me about static methods and said is that right that static method can't access or modify a class state?
General OO answer: the state of an object is the values of it's attributes. For example, given
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(42, 43)
then the state of p is {"x": 42, "y": 43}
To modify an object's state, a method need to have access to this object. For ordinary methods, this is provided by the self parameter.
Now Python's classes are objects too (instance of the type class), so Python has "classmethods" which can be invoked on either an instance or the class itself, but get the class object itself instead of an instance. Those classmethods can then modify the class's state (class attributes, which are shared by all instances of the class).
A staticmethod gets neither the instance nor class, so it can't change neither the class nor instance's state indeed.