Take the following class definition as an example:
# coding:utf-8
class A:
count = 0
def __init__(self, inst_name):
self.inst_name = inst_name
self.__class__.count += 1
def inst_method(self):
print ‘实例(%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() # 或 A.class_method()
a1.static_method() # 或 A.static_method()
Class instance method: The first argument is coerced to a class instance object, and the class property can be accessed through this class instance object, and the class properties can be accessed through the properties of the class instance object__class__.
def inst_method (self):
print ‘Instance (% s):% s’% (self .__ class __. count, self.inst_name)
Class instance methods do not require labeling, the first parameter is necessary, and the parser automatically passes the class instance object to the first parameter of the method.
The initialization method of the class__init__is also an instance method, which is called automatically when the instance is created. In this case, whenever an instance is initialized, it__class__accesses the class attribute count, which is added to the count 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 coerced to a class object, and the class property can be accessed through this class object, because the class instance property cannot be accessed because the class instance object is not passed in.
@classmethod
def class_method(cls):
print cls.count
Class methods need to useclassmethodannotations, the first parameter is necessary, and the parser automatically passes the class object to the first parameter of the method.
Class static methods: Unable to access class properties, class instance properties, and no default first parameter, it has nothing to do with the class, just a function bound in the class namespace.
@staticmethod
def static_method():
print ‘hello‘
Class static methods are typically used to define some functions related to a class topic.
You can call class methods, class static methods through class objects, but not class instance methods, or you can call three of these methods through class instance objects
a1,a2,a3,a4 = A(‘a1‘),A(‘a2‘),A(‘a3‘),A(‘a4‘)
a1.inst_method()
a1.class_method() # or A.class_method()
a1.static_method() # or A.static_method()
Python class instance methods, class methods, class static methods