What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object).
classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy.
It can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access self.
and accesses self.__class__.
only.
Think we have a class with b=2
, we will create an object and re-set this to b=4
in it.
Staticmethod cannot access nothing from previous.
Classmethod can access .b==2
only, via cls.b
.
Normal method can access both: .b==4
via self.b
and .b==2
via self.__class__.b
.
We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes self.attribute(s)
. There are languages where the OOP is implemented that way and I think it is not bad idea. :)