Python decorator @property

来源:互联网 发布:微课程视频制作软件 编辑:程序博客网 时间:2024/06/01 12:10

参考

廖雪峰的官方网站

http://blog.csdn.net/elevenqiao/article/details/6796770

 

Python version 3.4

1. 定义类Parrot

class Parrot(object):     def __init__(self):         self._voltage = 100000      def voltage(self):         """Get the current voltage."""         return self._voltage 

>>> s=Parrot()>>> s.voltage<bound method Parrot.voltage of <__main__.Parrot object at 0x01C66270>>>>> s.voltage()100000

访问voltage函数需要加括号才能得到期望的值100000, 否则返回的是一个函数类型。


2. 加上装饰器property之后,可以像访问属性那样访问函数,不用加括号调用。

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() #实例化类Parrot    # similarly invoke "getter" via @property 调用p.voltage() 相当于调用@property的getter方法    print (p.voltage)

调用的时候不用写成p.voltage(),写成p.voltage就可以。


3. 很多时候需要对类中的变量进行修改,需要一个函数做写入。

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, value):         """Set the current voltage."""         self._voltage = value
@voltage.setter 也是一个装饰器,使用了@property的setter方法去装饰voltage函数。

>>> s=Parrot()>>> s.voltage = 100>>> s.voltage100
赋值就调用setter, 没有赋值就调用getter。 可以任性使用s.voltage 。


附: 官方文档中对@property的说明:

class property(fget=None, fset=None, fdel=None, doc=None)

Return a propertyattribute.

fget is a function for getting an attribute value. fsetis a function for setting an attribute value.fdel is a function fordeleting an attribute value. Anddoc creates a docstring for theattribute.

A typical use is to define a managed attribute x:

class C:

    def __init__(self):

        self._x = None

 

    def getx(self):

        return self._x

 

    def setx(self, value):

        self._x = value

 

    def delx(self):

        del self._x

 

    x = property(getx,setx, delx, "I'm the 'x' property.")


If c is an instance of C, c.x will invoke the getter, c.x = value will invokethe setter and del c.x the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘sdocstring (if it exists). This makes it possible to create read-only properties easily using property() as adecorator:

class Parrot:

    def __init__(self):

        self._voltage= 100000

 

    @property

    def voltage(self):

        """Getthe current voltage."""

        return self._voltage


The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, andit sets the docstring forvoltage to “Get the current voltage.”

A property object has getter, setter, and deleter methods usable as decorators that create a copy of theproperty with the correspondingaccessor function set to the decorated function. This is best explained with anexample:

class C:

    def __init__(self):

        self._x = None

 

    @property

    def x(self):

        """I'mthe 'x' property."""

        return self._x

 

    @x.setter

    def x(self, value):

        self._x = value

 

    @x.deleter

    def x(self):

        del self._x


This code is exactly equivalent to the first example. Be sure to give theadditional functions the same name as the originalproperty (x in this case.)

The returned propertyobject also has the attributes fget, fset, and fdel corresponding to the constructor arguments.



这篇文章给出了更详细的说明,值得一读

-->http://www.programiz.com/python-programming/property


0 0