首页 > 代码库 > python中的property

python中的property

property(fget=None, fset=None, fdel=None, doc=None) -> property attributefget is a function to be used for getting an attribute value, and likewisefset is a function for setting, and fdel a function for deling, anattribute.  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.__xa=haha()print(a.x)a.x=hahaprint(a.x)del a.xprint(a.x)

 输出为

x.getterweidiaox.setterx.getterhahax.deleterx.getterTraceback (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.__xAttributeError: haha object has no attribute _haha__x

 

python中的property