关于python的成员方法,类方法,静态方法

143 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第12天,点击查看活动详情

例子分析

参照下面这个例子来了解这4种方法。

>>> class Root:
__total=0
def_init(self,v): #构造方法 
    seif. value =v 
    Root. total+=1

def show(self): #普通实例方法 
    print('self. value:',self. value) 
    print('Root. total:',Root. total)

@classmethod #修饰器,声明类方法 
def classShowTotal(cls):#类方法
    print(cls. total)

@staticmethod #修饰器,声明静态方法 
def staticShowTotal(): #静态方法 
    print(Root. total)

>>>r=Root(3)
>>>r.classShowTotal() #通过对象来调用类方法 
>>>r.staticshowTotal() #通过对象来调用静态方法 
1
>>> r.show()
self._value:=3 
Root. total=1
>>>rr=Root(5)
>>>Root.classShowTotal() #通过类名调用类方法 
2
>>>Root.staticShowTotal() #通过类名调用静态方法 
2
>>>Root.show() #试图通过类名直接调用实例方法,失败 
TypeError: unbound method show() must be called with Root instance as first argument (got nothing instead)

>>> Root.show(r) #但是可以通过这种方法来调用方法并访问实例成员 
self. value=3 
Root. total=2
>>>Root.show(rr)#通过类名调用实例方法时为self参数显式传递对象名 
self. value=5 
Root. total=2

成员方法

成员方法有:对象的成员方法,类的成员方法。

seif. value =v 

这个就是对象的成员方法。对象的成员方法比较多,像def show(self):也是对象的成员方法。所以说,有self的就是对象的成员方法。

 Root. total+=1

像这个就是类的成员方法。

__total=0

这种没有写在方法里的,叫做类的数据成员。

类方法

@classmethod  
def classShowTotal(cls):  #类方法
    print(cls. total)

这个是类的方法,定义类的方法需要加@classmethod 修饰器,用于声明是类的方法。括号中clsclass的缩写。

静态方法

@staticmethod #修饰器,声明静态方法 
def staticShowTotal(): #静态方法 
    print(Root. total)

像静态方法的话,括号里没有东西且前面修饰器为@staticmethod 。类方法和静态方法需要加修饰器来声明是什么方法。

三个方法的功能差异

对象的成员方法可以对对象的数据成员和类的数据成员进行操作,换句话说,对象成员可以调用任何成员。类方法和静态方法只能调用类的成员。

>>>Root.show() #试图通过类名直接调用实例方法,失败 
TypeError: unbound method show() must be called with Root instance as first argument (got nothing instead)

像这种用类调用对象成员方法是错误的,这样会报错。