+ 4
@staticmethod and @classmethod
The Python OOP tutorial was quite confusing. Can someone please explain @classmethod and @staticmethod. I am writing more Python programs which are object oriented but @classmethod method and @staticmethod really threw me.
1 Resposta
+ 5
A method normally defined takes 'self' as an implicit first argument.
A classmethod takes the class as an implicit first argument.
You can use this for example when you have class variables (variables that all instances share) like an instance counter.
If a method of an instance tries to change such a class variable by referring to it with self., it will instead override the class variable.
So a class method would be one way to change class content instead of instance content.
As a habit, you use 'cls' now instead of 'self' but it could be anything.
A static method doesn't implicitly pass anything, neither instance nor class. So it is basically the same as a regular free function, only that it's formally part of a class.