说到装饰器,就不得不说python自带的三个装饰器:python
一、@property 将某函数,作为属性使用函数
@property 修饰,就是将方法,变成一个属性来使用。学习
class A(): @property def pfunc(self): return self.value @pfunc.setter def pfunc(self,value): self.value = value @property def pfunc1(self): print('this is property') if __name__=="__main__": A.pfunc = 9 print A.pfunc A.pfunc1
二、@classmethod 修饰类的方式this
带修饰类方法:cls作为方法的第一个参数,隐式的将类作为对象,传递给方法,调用时无须实例化。spa
普通函数方法:self作为第一个参数,隐式的将类实例传递给方法,调用方法时,类必须实例化。code
class A(): def func(self,x,y): return x * y @classmethod def cfunc(cls,x,y): return x * y
if __name__=="__main__": print A().func(5,5) print A.cfunc(4,5)
三、@staticmethod 修饰类的方式对象
1)是把函数嵌入到类中的一种方式,函数就属于类,同时代表函数不须要访问这个类blog
2)使用修饰服,修饰方法,不须要实例化class
class A(): def func(self,x,y): return x * y @staticmethod def sfunc(x,y): return x * y if __name__=="__main__": print A.sfunc(6,5)
Linux and python学习交流1,2群已满.方法
Linux and python学习交流3群新开,欢迎加入,一块儿学习.qq 3群:563227894
不前进,不倒退,中止的状态是没有的.
一块儿进步,与君共勉,