Python黑魔法之property装饰器详解
@property装饰器可以将一种方法调用为属性。让我们来看看Python黑魔法@property装饰器的使用技巧分析
@property有什么用?从表面上看,它是通过属性访问一种方法.
代码最清晰,代码最清晰.
classCircle(object): def__init__(self,radius): self.radius=radius @property defarea(self): return3.14*self.radius**2 c=Circle(4) printc.radius printc.area
可以看出,虽然area被定义为一种方法形式,但在添加@property后,可以直接进行carea.area,作为属性访问.
现在问题来了,每次调用c.area,会计算一次,太浪费cpu了,怎么才能只计算一次?这是lazy property.
classlazy(object): def__init__(self,func): self.func=func def__get__(self,instance,cls): val=self.func(instance) setattr(instance,self.func.__name__,val) returnval classCircle(object): def__init__(self,radius): self.radius=radius @lazy defarea(self): print'evalute' return3.14*self.radius**2 c=Circle(4) printc.radius printc.area printc.area printc.area
'evalute'只输出一次,应该很好地理解@lazy的机制。.
lazy类在这里有___get__方法,说明是描述器,第一次执行c.area时,由于顺序问题,先去crea.__dict__________________________get__拦截.
在__get___________________________.__dict__中去.
再次执行c.area的时候,先去crea.__dict_______________________get__了.
注意点
请注意以下代码场景:
代码片段1:
classParrot(object): def__init__(self): self._voltage=100000 @property defvoltage(self): """Getthecurrentvoltage.""" returnself._voltage if__name__=="__main__": #instance p=Parrot() #similarlyinvoke"getter"via@property printp.voltage #update,similarlyinvoke"setter" p.voltage=12
代码片段2
classParrot: def__init__(self): self._voltage=100000 @property defvoltage(self): """Getthecurrentvoltage.""" returnself._voltage if__name__=="__main__": #instance p=Parrot() #similarlyinvoke"getter"via@property printp.voltage #update,similarlyinvoke"setter" p.voltage=12
代码1、2的区别在于
class Parrot(object):
在python2下,分别运行测试
片段1:这将提示一个预期的错误信息 AttributeError: can't set attribute
片段2:正确运行
参考python2文件,@property将提供ready-only property,上述代码未提供相应的代码@voltage.setter,在python2文档中,我们可以找到以下信息:
BIF:
property([fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
原来在python2下,内置类型 object 这不是默认的基本类别。如果在定义类别时没有明确解释(代码片段2),我们定义的parrot(代码片段2)将不会继承object
object类只提供了我们需要的@property功能,我们可以在文档中找到以下信息:
new-style class
Any class which inherits from object. This includes all built-in types like list and dict. Only new-style classes can use Python's newer, versatile features like __slots__, descriptors, properties, and __getattribute__().
同时,我们也可以通过以下方法来验证
classA: pass >>type(A) <type'classobj'>
classA(object): pass >>type(A) <type'type'>
从返回的<type 'classobj'>,<type 'type'>可以看出<type 'type'>object类型是我们需要的(python 3.0 将object类作为默认基类,因此将返回<type 'type'>)
python是为了考虑代码 对于版本过渡期的兼容性,我认为在定义class文件时,应该明确定义object作为一个好习惯
最后的代码将如下
classParrot(object): def__init__(self): self._voltage=100000 @property defvoltage(self): """Getthecurrentvoltage.""" returnself._voltage @voltage.setter defvoltage(self,new_value): self._voltage=new_value if__name__=="__main__": #instance p=Parrot() #similarlyinvoke"getter"via@property printp.voltage #update,similarlyinvoke"setter" p.voltage=12
此外,@property在2.6、3.0新增,2.5无此功能。