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
posted @ 2022-02-05 22:48  chuangzhou  阅读(88)  评论(0编辑  收藏  举报