python利用property装饰器设置只读属性,pythonproperty,如果我们需要设置只读取属


如果我们需要设置只读取属性,那么不需要set方法即可实现属性的只读。

class C(object):    def __init__(self):        self.__x = 10    @property    def x(self):        return self.__xif __name__ == "__main__":    c = C()    print c.x    c.x = 10———- python ———-10Traceback (most recent call last):File “F:\test.py”, line 14, inc.x = 10AttributeError: can’t set attribute

输出完成 (耗时 0 秒) – 正常终止

访问类或实例的属性时是直接通过obj.XXX的形式访问,但property是一个特性的属性,访问添加了装饰器@property的方法时无须额外添加()来调用,而是以属性的形式来访问。所以,利用这个特性可以虚拟实现类属性的只读设置。

实际上文中实例的x的属性还是可以通过 c._C__x = 20 的形式来改值。若要彻底拒绝被改变,则删除带双下划线的__x属性:

class C(object):    @property    def x(self):        return 10if __name__ == "__main__":    c = C()    print c.x    c.x = 10

评论关闭