编程语言
首页 > 编程语言> > Python - 让实例属性不可变(只读)

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 修饰的函数, 所以b.name= 为修改值的操作
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>> b.age = 18   
>>> b.age
18

标签:__,...,.__,name,只读,Python,self,实例,wangfu
来源: https://www.cnblogs.com/czzz/p/15865027.html