美文网首页
python @property,setter,deleter

python @property,setter,deleter

作者: comboo | 来源:发表于2017-04-07 18:04 被阅读38次

在创建对象的时候,有时候我们不想让别人修改对象的属性。可以用这个方法。

property直接声明变量属性,可以理解为声明一个只读对属性

setter声明对象可以修改

deleter删除属性

#python3环境
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):
        # print('see you!')
        del self._x

#注意调用
c = C()                #实例化对象
c._x = 30            #改变_x属性的值,因为有@x.setter,所以可以使用
print(c._x)           #30
del c._x               #删除
# print(c._x)         #AttributeError: 'C' object has no attribute '_x'

相关文章

网友评论

      本文标题:python @property,setter,deleter

      本文链接:https://www.haomeiwen.com/subject/imohattx.html