码迷,mamicode.com
首页 > 编程语言 > 详细

Python @property 属性

时间:2017-04-12 09:32:11      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:使用   内置函数   ons   targe   对象   python   返回   htm   val   

Python @property 修饰符

 

python的property()函数,是内置函数的一个函数, 会返回一个property的属性: 可以在以下网页查看它的描述:property

文档上面说property()作为一个修饰符, 这会创建一个只读的属性.

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

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

在这里面, @property修饰符会将voltage()方法转变为一个对于只读的属性"getter", 它还会将voltage的docstring设置为"Get the current voltage"

class C:
    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

c = C()
c.X = 2
print(c.X)
print(c._x)
# 2
# 2

 

这个代码也能够使用非修饰符的方法来写, 请看下面

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.")

c = C()
c.X = 2
print(c.X)
print(c._x)
# 2
# 2

这两段代码的意思, 就是通过property()设置了一个管理self._x的属性的函数, 以后管理_x, 都可以通过X这个property对象.

Python @property 属性

标签:使用   内置函数   ons   targe   对象   python   返回   htm   val   

原文地址:http://www.cnblogs.com/hwy89289709/p/6697507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!