property、classmethod和staticmethod总结

我们知道只要在类内部定义的,并且没有被任何装饰球修饰过的方法,都是绑定到对象的绑定方法。实例化的对象调用绑定方法时,会把对象作为第一个参数self自动传入。

 1 class People:
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5     def walk(self):#绑定到对象的方法 
 6         print("%s is walking"%self.name)
 7     def say(self):#绑定到对象的方法 
 8         print("%s is walking"%self.name)
 9 
10 f = People("Grace",18)
11 f.walk()
12 f.say()
13 print(f.walk)

@classmethod

这是绑定到类的方法,专门给类调用。调用方式:类名.绑定到类的方法(),把类名作为第一个参数cls传入。

 1 class Solider:
 2     def __init__(self,level,coutry):
 3         self.level = level
 4         self.coutry = coutry
 5 
 6     @classmethod
 7     def US_solider(cls): #绑定到类的方法
 8         "大规模产生A等级美国士兵对象"
 9         US_A = Solider("A_level","USA")
10         return US_A
11 
12     def attack(self):
13         print("%s soilder start to attack"%self.coutry)
14 
15 us1 = Solider.US_solider()
16 print(us1.coutry)
17 print(us1.__dict__)
18 print(Solider.US_solider) #绑定到类的方法
19 print(us1.attack)#绑定到对象的方法

@staticmethod

类里面定义的函数属性,除了绑定到对象、绑定到类,还可以通过@staticmethod解除绑定。这个函数则类似普通函数,相当于一个工具包。这样就没有自动传值的功能了。

 1 lass Weather:
 2     def __init__(self,air,wet,temperature):
 3         self.air = air
 4         self.wet = wet
 5         self.temperature = temperature
 6     @staticmethod
 7     def nomal_spring():
 8         print("the nomal spring wether:sunshine,the wet: 40,the temperature:15")
 9 
10 
11 bj1 = Weather("sunshine",30,18)
12 bj1.nomal_spring() #对象可以调用
13 Weather.nomal_spring()#类也可以调用

@property

property是一种特殊的属性。
它的作用:
1、实例化对象调用方法时,不需要额外添加()进行调用方法
2、遵循了"统一访问原则",避免使用方法时产生混乱。
@property,还可以封装属性,配合setter、deleter,对属性的查找、修改、删除进行自定义。

 1 class Foo:
 2     def __init__(self,name):
 3         self.__name = name
 4     @property
 5     def name(self):
 6         return self.__name
 7     @name.setter
 8     def name(self,value):
 9         self.__name = value
10 
11     @name.deleter
12     def name(self):
13         del self.__name
14 
15 
16 f = Foo("maple")
17 f.name = "allen"
18 print(f.name)
19 print(Foo.name(f))
原文地址:https://www.cnblogs.com/greatkyle/p/6757026.html