Today, when I read the code, I found that Python's class definition mentions the @classmethod modifier, and then looks at some of the material to find out, let's make a summary.
The mention of Classmethod in Python refers to Staticmethod, not because of the relationship between the two, but to make the user differentiate to write code more clearly. In C + +, we understand that a function accessed directly through a class name is called a static function of a class, that is, a function of static modification, and that Classmethod and Staticmethod in C + + are a concept.
So what's the difference between the two in Python? Let's look at how the two are declared in the Python code:
Class MyClass:
...
Modifier for @classmethod # Classmethod
Def class_method (CLS, arg1, Arg2, ...):
...
Modifier for @staticmethod # Staticmethod
def static_method (arg1, Arg2, ...):
...
For Classmethod parameters, it is necessary to implicitly pass the class name, while the Staticmethod parameter does not need to pass the class name, in fact, this is the biggest difference between the two.
Both can be invoked through class names or class instance objects, because the emphasis is on Classmethod and Staticmethod, so it's best to use class names when writing code, good programming habits.
For Staticmethod to be set in order to be defined in the class, this is generally rarely used, and can be replaced with a module-level (Module-level) function. Since it is to be defined in a class, it must be considered by the author.
For Classmethod, you can redefine them by subclasses.
refers to class-level functions, and incidentally mentions class-level variables
Class MyClass:
i = 123 # Class-level variable
def __init__ (self):
SELF.I = 456 # object-level Variable
...
...
The best way to clearly differentiate the top two I is to take into account that everything in Python is object, so i=123 belongs to class object, i=456 belongs to class instance object