Python的类实例方法,类方法,类静态方法

时间:2023-03-09 20:07:00
Python的类实例方法,类方法,类静态方法

以下面的类定义为例:

# 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__属性访问类属性。

def inst_method(self):
print '实例(%s):%s' % (self.__class__.count, self.inst_name)

类实例方法不需要标注,第一个参数必不可少,解析器自动会将类实例对象传给方法的第一个参数。

类的初始化方法__init__也是实例方法,在实例创建的时候自动调用。在这里每当初始化一个实例,就通过__class__来访问类属性count,是它加一,用来统计类的实例数。

def __init__(self, inst_name):
self.inst_name = inst_name
self.__class__.count += 1

类方法:第一个参数强制为类对象,可以通过这个类对象访问类属性,由于没有传入类实例对象,所以不能访问类实例属性。

@classmethod
def class_method(cls):
print cls.count

类方法需要使用classmethod标注,第一个参数必不可少,解析器自动会将类对象传给方法的第一个参数。

类静态方法:无法访问类属性、类实例属性、没有默认的第一个参数,其实跟类没什么关系,只是绑定在类命名空间下的函数而已。

@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()