静态⽅法和类⽅法
1. 类⽅法
是类对象所拥有的⽅法,需要⽤修饰器 @classmethod 来标识其为类⽅法,对于类⽅法,第⼀个参数必须是类对象,⼀般以 cls 作为第⼀个参数(当然
可以⽤其他名称的变量作为其第⼀个参数,但是⼤部分⼈都习惯以'cls'作为第
⼀个参数的名字,就最好⽤'cls'了),能够通过实例对象和类对象去访问。
class People(object): country = 'china' #类⽅法,⽤classmethod来进⾏修饰 @classmethod def getCountry(cls): return cls.country p = People() print p.getCountry() #可以⽤过实例对象引⽤ print People.getCountry() #可以通过类对象引⽤
类⽅法还有⼀个⽤途就是可以对类属性进⾏修改:
class People(object): country = 'china' #类⽅法,⽤classmethod来进⾏修饰 @classmethod def getCountry(cls): return cls.country @classmethod def setCountry(cls,country): cls.country = country
p = People() print p.getCountry() #可以⽤过实例对象引⽤ print People.getCountry() #可以通过类对象引⽤ p.setCountry('japan') print p.getCountry() print People.getCountry()
了改变
2. 静态⽅法
需要通过修饰器 @staticmethod 来进⾏修饰,静态⽅法不需要多定义参数class People(object): country = 'china' @staticmethod #静态⽅法 def getCountry(): return People.country
print People.getCountry()
总结
从类⽅法和实例⽅法以及静态⽅法的定义形式就可以看出来,类⽅法的第⼀
个参数是类对象cls,那么通过cls引⽤的必定是类对象的属性和⽅法;⽽实例
⽅法的第⼀个参数是实例对象self,那么通过self引⽤的可能是类属性、也有
可能是实例属性(这个需要具体分析),不过在存在相同名称的类属性和实
例属性的情况下,实例属性优先级更⾼。静态⽅法中不需要额外定义参数,
因此在静态⽅法中引⽤类属性的话,必须通过类对象来引⽤