class A(): method = 'class' #实例方法 def normethod(self): print('I am the normal method') #静态方法 @staticmethod def stamethod(): print ('I am the static method') #类方法 @classmethod def clsmethod(cls): print (f'I am the {cls.method} method')
实例方法第一个参数是 self,它表示实例化后类的地址id,所以需要一个类的实例,才能调用这个函数
1 2 3 4
>>> A.normethod() #直接这样调用会报错 >>> a = A() >>> a.normethod() #需要实例化后传递进 id 参数才能调用 I am the normal method
>>> A.stamethod() #静态方法不用实例化可直接调用 I am the static method >>> a = A() >>> a.stamethod() #也可以实例化后再调用 I am the static method
静态方法最大的优点是能节省开销,因为它不会绑定到实例对象上,它在内存中只生成一个。
1 2 3 4 5 6 7 8 9 10 11
>>> a1 = A() >>> a2 = A() >>> a1.stamethod <function static at 0x0000000004938E48> >>> a2.stamethod <function static at 0x0000000004938E48> >>> A.stamethod <function static at 0x0000000004938E48> >>> >>> a1.stamethod is A.stamethod and a2.stamethod is A.stamethod True
而实例方法每个实例对象都是独立的,开销较大
1 2 3 4 5 6
>>> a1.normethod <bound method A.norstatic of <__main__.A instance at 0x0000000004590AC8>> >>> a2.normethod <bound method A.norstatic of <__main__.A instance at 0x00000000045901C8>> >>> a1.normethod is a2.normethod False
评论已关闭