Python class instance method, class method, class static method,
The following class definition is used as an example:
# Coding: utf-8class A: count = 0 def _ init _ (self, inst_name): self. inst_name = inst_name self. _ class __. count + = 1 def inst_method (self): print 'instance (% s): % s' % (self. _ class __. count, self. inst_name) @ classmethod def class_method (cls): print cls. count @ staticmethod def static_method (): print 'Hello 'a1, a2, a3, a4 = A ('a1'), A ('a2 '), A ('a3 '), A ('a4') a1.inst _ method () a1.class _ method () # Or. class_method () a1.static _ method () # Or. static_method ()
Class instance method: the first parameter is forced to be a class instance object. You can use the class property of this class instance object, you can use the class instance object's__class__
Property category attributes.
Def inst_method (self): print 'instance (% s): % s' % (self. _ class _. count, self. inst_name)
The class instance method does not need to be labeled. The first parameter is required, and the parser automaticallyClass Instance ObjectThe first parameter passed to the method.
Class Initialization Method__init__
It is also an instance method that is automatically called when an instance is created. Every time an instance is initialized__class__
To calculate the number of instances of the class.
def __init__(self, inst_name): self.inst_name = inst_name self.__class__.count += 1
Class method: the first parameter is forced to be a class object. You can use the class object category class attribute. Because the class instance object is not passed in, the class instance attribute cannot be used.
@classmethoddef class_method(cls): print cls.count
Class method needs to be usedclassmethod
Annotation, the first parameter is indispensable, and the parser will automatically pass the class object to the first parameter of the method.
Static class method: the class attributes, class instance attributes, and no default first parameter are not allowed. In fact, it has nothing to do with the class, but it is only a function bound to the class namespace.
@staticmethoddef static_method(): print 'hello'
Static class methods are usually used to define functions related to Class themes.
You can call Class and Class static methods through class objects, but cannot call class instance methods. You can call the above three methods through class instance objects.
A1, a2, a3, a4 = A ('a1'), A ('a2 '), A ('a3'), A ('a4') a1.inst _ method () a1.class _ method () # Or. class_method () a1.static _ method () # Or. static_method ()