Kev*_*tle 8 python attributes readonly
在Python中,我想让类的选定实例属性只读取到类之外的代码.我希望外部代码无法改变属性,除非间接地通过调用实例上的方法.我希望语法简洁.什么是最好的方法?(我现在给出我目前最好的答案......)
你应该使用@property装饰器.
>>> class a(object):
... def __init__(self, x):
... self.x = x
... @property
... def xval(self):
... return self.x
...
>>> b = a(5)
>>> b.xval
5
>>> b.xval = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |