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

python中的property

时间:2016-10-30 23:57:01      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:user   main   pre   color   pycharm   erro   elf   内容   delete   

property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for deling, an
attribute.  Typical use is to define a managed attribute x:

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

Decorators make defining new properties or modifying existing ones easy:

class C(object):
    @property
    def x(self):
        "I am the ‘x‘ property."
        return self._x
    @x.setter
    def x(self, value):
        self._x = value
    @x.deleter
    def x(self):
        del self._x

安装ipython,使用cmder,输入property?,就会看到以上内容.

定义property有两种方式,一种是使用class property,它位于builtin,是一种class.另一种方式是使用注解.

下面测试一下,是否真的调用了setter和getter

class haha:
    def __init__(self):
        self.__x=weidiao
    @property
    def x(self):
        print("x.property")
        return self.__x
    @x.getter
    def x(self):
        print("x.getter")
        return self.__x
    @x.setter
    def x(self,x):
        print("x.setter")
        self.__x=x
    @x.deleter
    def x(self):
        print(x.deleter)
        del self.__x
a=haha()
print(a.x)
a.x=haha
print(a.x)
del a.x
print(a.x)

 输出为

x.getter
weidiao
x.setter
x.getter
haha
x.deleter
x.getter
Traceback (most recent call last):
  File "C:/Users/weidiao/Documents/PycharmProjects/python实验室/main2.py", line 25, in <module>
    print(a.x)
  File "C:/Users/weidiao/Documents/PycharmProjects/python实验室/main2.py", line 11, in x
    return self.__x
AttributeError: haha object has no attribute _haha__x

 

python中的property

标签:user   main   pre   color   pycharm   erro   elf   内容   delete   

原文地址:http://www.cnblogs.com/weidiao/p/6014191.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!