该简单代码可展示@staticmethod、@classmethod、@property的基本使用方法:
1 class Animal(object): 2 name = "monkey" 3 def __init__(self,name): 4 self.name = name 5 6 @staticmethod #静态方法,使方法脱离类,只是名义上属于该类 7 def doing(self): 8 print("%s is %s"% (self.name,'running')) 9 10 @classmethod #类方法,参数只能获取类变量,不能获取实例变量 11 def doing(self): 12 print("%s is %s"% (self.name,'running')) 13 14 @property #属性方法,把一个方法变为静态属性 15 def doing(self): 16 print("%s is %s"% (self.name,'running')) 17 @doing.setter #设置doing方法,是doing方法可以传参 18 def doing(self,dosomething): 19 print("%s is %s"% (self.name,dosomething)) 20 @doing.deleter 21 def doing(self): 22 print("It had been removed...") 23 24 #静态方法调用 25 a = Animal("lion") 26 a.doing(a) #把a传给self参数 27 28 #类方法调用 29 a = Animal("lion") 30 a.doing() 31 32 #属性方法无参数直接调用 33 a = Animal("lion") 34 a.doing 35 36 #属性方法有参数调用 37 a = Animal("lion") 38 a.doing = "hunting" 39 40 #属性方法删除 41 a = Animal("lion") 42 del a.doing
注:注释部分代码运行