There are 3 ways to define a class method in Python, a general way, @classmethod adornment, @staticmethod adornment.
classA (object):deffoo (self, x):Print("executing foo (%s,%s)"%(self, x))Print('Self :', self) @classmethoddefClass_foo (CLS, x):Print("executing Class_foo (%s,%s)"%(CLS, x))Print('CLS:', CLS) @staticmethoddefStatic_foo (x):Print("executing static_foo (%s)"%x) a= A ()1. How to define
The Normal class method Foo () needs to pass an instance of the current class object implicitly through the self parameter. The method of @classmethod modification Class_foo () needs to pass the current class object through a CLS parameter. The method definition @staticmethod modified is the same as the normal function.
The difference between self and CLS is not mandatory, just a programming style in PEP8, self is usually used as the first parameter of an instance method, and the CLS is typically used as the first parameter of a class method. That is, you typically pass an instance of the current class object with self, and the CLS passes the current class object.
2. Binding objects
foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定。
Print (A.foo)<bound method A.foo of <__main__print(a.class_foo)<bound method A.class_foo of <class'__main__. A'print(a.static_foo)<function A.static_foo at 0x02780390>
3. Invocation mode
Foo can be called by instance a, and the class will have a parameter error in calling directly like a.
>>> A.foo (1) executing foo (<__main__. A object at 0x0278b170>,1<__main__. A object at 0x0278b170>>>> a.foo (1) Traceback (most recent call last): "<stdin >" in <module>'x'
But Foo can use normal, explicit pass-through instance parameter a as follows.
>>> A.foo (A, 1) executing foo (<__main__. A object at 0x0278b170>,1<__main__. A Object at 0x0278b170>
Class_foo is called through a class object or object instance.
>>> A.class_foo (1) executing Class_foo (<class'__main__. A'>,1<class'__main__. A'>>>> a.class_foo (1) executing Class_foo (<class' ) __main__. A'>,1<class'__main__. A'>
Static_foo is called through a class object or object instance.
>>> A.static_foo (1) executing static_foo (1)>>> a.static_foo (1) executing Static_foo (1)
4. Inheritance is the same as overriding normal class functions.
class B (A): pass b = b () B.foo ( 1 ) B.class_foo ( 1 1) # executing foo ( <__main__. B object at 0x007027d0>,1) # self: <__ main__. B object at 0x007027d0> # executing class _foo (<class ' __main__. B ' >,1) # cls: <class ' __main__. B '; # executing static_foo (1)
Problem: @staticmethod modified method functions and normal out-of-class functions, why not use normal functions directly?
@staticmethod is one way to embed a function in a class, and the function belongs to the class, indicating that the function does not need to access the class. By inheriting the subclass, the code can be better organized.
@classmethod @staticmethod differences in Python