Python - 让实例属性不可变(只读)
>>> class A:
... def __init__(self,name):
... self.__name = name
...
>>> a = A('xiaoming')
>>> a.name # 私有化,外部不能直接访问
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'name'
>>> a.name = 'wangfu' # 为实例a 增加了一个新的公开name属性
>>> a.name
'wangfu'
>>> a.__dict__
{'_A__name': 'xiaoming', 'name': 'wangfu'}
>>> class B:
... def __init__(self,name):
... self.__name = name
... @property # 提供访问
... def name(self):
... return self.__name
...
>>> b = B('张三')
>>> b.name
'张三'
>>> b.name = '李四' # 因为没有@property.set 修饰的同名函数, 所以报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> b.age = 18
>>> b.age
18
本文来自博客园,作者:chuangzhou,转载请注明原文链接:https://www.cnblogs.com/czzz/p/15865027.html