python利用property装饰器设置只读属性,pythonproperty,如果我们需要设置只读取属
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
相关内容
- python字符串内置方法,python字符串内置,在这一篇文章中
- python处理gzip压缩的http数据,pythongzip,其实关于这个内容
- Python使用gzip压缩数据包,pythongzip数据包,将数据使用
- 使用pyinstaller打包python为exe文件,pyinstallerpython,使用p
- python tkinter 窗口居中对齐,pythontkinter,tkinter没有现成的
- Python Hello world,pythonhelloworld,#!/usr/bin/p
- python 连接 sqlalchemy orm库查询示例,sqlalchemyorm,python 连接
- Python计算24点代码,python计算24点,下面的代码通过算2
- 使用Python做数值运算,python数值运算,#!/usr/bin/p
- Python 使用字符串,python使用字符串,如下代码演示Pyth
评论关闭