Python黑魔法@property装饰器的使用技巧解析
@property有什么用呢?表面看来,就是将一个方法用属性的方式来访问. class Circle(object): def __init__(self,radius): self.radius = radius @property def area(self): return 3.14 * self.radius ** 2 c = Circle(4) print c.radius print c.area 可以看到,area虽然是定义成一个方法的形式,但是加上@property后,可以直接c.area,当成属性访问. class lazy(object): def __init__(self,func): self.func = func def __get__(self,instance,cls): val = self.func(instance) setattr(instance,self.func.__name__,val) return val class Circle(object): def __init__(self,radius): self.radius = radius @lazy def area(self): print 'evalute' return 3.14 * self.radius ** 2 c = Circle(4) print c.radius print c.area print c.area print c.area 可以看到,'evalute'只输出了一次.如果看了我前面几篇博文,对@lazy的机制应该很好理解. 注意点 代码片段1: class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update,similarly invoke "setter" p.voltage = 12 代码片段2: class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update,similarly invoke "setter" p.voltage = 12 代码1、2的区别在于 class Parrot(object): 在python2.6下,分别运行测试 参考python2.6文档,@property将提供一个ready-only property,以上代码没有提供对应的@voltage.setter,按理说片段2代码将提示运行错误,在python2.6文档中,我们可以找到以下信息: BIF: 而object类正好提供了我们需要的@property功能,在文档中我们可以查到如下信息: new-style class 同时我们也可以通过以下方法来验证 class A: pass >>type(A) <type 'classobj'> Python 2.6代码 class A(object): pass >>type(A) <type 'type'> 从返回的<type 'classobj'>,<type 'type'>可以看出<type 'type'>是我们需要的object类型(python 3.0 将object类作为默认基类,所以都将返回<type 'type'>) 为了考虑代码的python 版本过渡期的兼容性问题,我觉得应该定义class文件的时候,都应该显式定义object,做为一个好习惯 最后的代码将如下: class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage @voltage.setter def voltage(self,new_value): self._voltage = new_value if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update,similarly invoke "setter" p.voltage = 12 另外,@property是在2.6、3.0新增的,2.5没有该功能。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |