python -- property()/@property

https: //docs.python.org/2/library/functions.html?highlight=property#property


property()

      property ( [ fget [, fset [, fdel [, doc ] ] ] ] )

Return a property attribute for new-style classes (classes thatderive fromobject).

fget 用于获取属性值,  fset 用于设置属性值,  fdel 用于删除属性 . 传统的用法, 主要用于定义属性, 例如: 

class C(object):
    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.")

如果 cC 的一个实例, c.x 将会调用函数 getter, 即上面的getxc.x= value 会调用 setter, 即setx;del c.x 会调用 deleter, 即delx.

doc 是属性的 docstring 字符串. 如果未设置 doc, 默认将会使用 fget‘s docstring (如果存在). 使用 property() 作为修饰, 可以创建只读属性:

class Parrot(object):
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

可以将 voltage() 方法变为 “getter”, 一个同名的只读属性.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@property

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

此处代码等效于第一个例子. 请确保函数名相同 (此处都是 x .)

返回值,拥有属性 fget, fset, fdel

New in version 2.2.

2.5 版: 若无 doc, 则使用fget‘s docstring .

2.6 版: 添加属性 getter,setterdeleter .

============================================================================================

下面给出一个实际的运用案例, 代码取自scrapy:

    @property
    def meta(self):
        if self._meta is None:
            self._meta = {}
        return self._meta

    def _get_url(self):
        return self._url

    def _set_url(self, url):
        if isinstance(url, str):
            self._url = escape_ajax(safe_url_string(url))
        elif isinstance(url, unicode):
            if self.encoding is None:
                raise TypeError('Cannot convert unicode url - %s has no encoding' %
                    type(self).__name__)
            self._set_url(url.encode(self.encoding))
        else:
            raise TypeError('Request url must be str or unicode, got %s:' % type(url).__name__)
        if ':' not in self._url:
            raise ValueError('Missing scheme in request url: %s' % self._url)

    url = property(_get_url, obsolete_setter(_set_url, 'url'))



你可能感兴趣的:(python)