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

property属性[Python]

时间:2014-07-29 21:35:22      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   数据   for   

一、property解释

  根据文档资料解释

property([fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object)

  使用这个内建函数时,类必须继承object,才有效。

  property有可选参数fget, fset, fdel, doc。fget是获取值函数,fset是设置函数值,fdel是删除函数,doc文档说明。

二、例子

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, ‘‘)

c = C()
c.x = 1
print c.x
del c.x

另外一种表达方式,property作为一种装饰器使用:

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

    @property
    def voltage(self):
        return self._voltage

    @voltage.setter
    def voltage(self, value):
        self._voltage = value

    @voltage.deleter
    def voltage(self):
        del self._voltage

p = Parrot()
print p.voltage
p.voltage = 1
del p.voltage

property函数使用对类属性的读取更简洁,隐藏了变量,保证了数据的安全。

property属性[Python],布布扣,bubuko.com

property属性[Python]

标签:style   blog   http   color   使用   io   数据   for   

原文地址:http://www.cnblogs.com/zhuangzebo/p/3876327.html

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