python静态方法、类方法
常规:
1 class Dog(object): 2 def __init__(self,name): 3 self.name=name 4 5 def eat(self): 6 print('%s is eating'%self.name) 7 8 d1=Dog('lele') 9 d1.eat()
1.静态方法:名义上由类管理,而实际在调用时,需要手动把实例对象传进去作参数
1 class Dog(object): 2 def __init__(self,name): 3 self.name=name 4 @staticmethod 5 def eat(self): 6 print('%s is eating'%self.name) 7 8 d1=Dog('lele') 9 d1.eat(d1)
2.类方法:只能访问类变量,不能访问实例变量
1 class Dog(object): 2 name='xiaomei' 3 def __init__(self,name): 4 self.name=name 5 6 @classmethod 7 def eat(self): 8 print('%s is eating'%self.name) 9 10 d1=Dog('lele') 11 d1.eat()
实例变量name='lele',类变量name='xiaomei'。
调用结果为:xiaomei is eating
3.属性方法:把一个方法变为一个静态属性(用途:用户只需要知道查询结果(调用属性),而复杂的实现过程不需要用户知道。eg:第三方查询航班)
1 class Dog(object): 2 def __init__(self,name): 3 self.name=name 4 5 6 @property 7 def eat(self): 8 print('%s is eating'%self.name) 9 10 d1=Dog('lele') 11 d1.eat
lele is eating
若要增加参数,可以通过 @属性方法名.setter 来实现
class Dog(object): def __init__(self,name): self.name=name self.__food=None #将一个方法变为静态属性 @property def eat(self): print('%s is eating %s' % (self.name,self.__food)) #更改属性方法 @eat.setter def eat(self,food): #增加了参数 self.__food=food print('%s is eating %s' % (self.name, self.__food)) #删除属性方法 @eat.deleter def eat(self): del self.__food print('已删除') d1=Dog('lele') d1.eat d1.eat='gutou' #变成静态属性后,注意赋值方式 d1.eat del d1.eat
lele is eating None
lele is eating gutou
lele is eating gutou
已删除