如何使类不可变在python? [英] How to make class immutable in python?
本文介绍了如何使类不可变在python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里阅读了很多关于这个主题,但我还是找不到一个合适的答案。
我有一个类如下:
I have read a lot about this subject here but i still can't find an appropriate answer. I have a class like:
class A(object):
def __init__(self, first, second):
self.first = first
self.second = second
def __eq__(self, other):
return ****
def __str__(self):
return *****
def __repr__(self):
return ****
a = A("a", "b")
a.first =cfor example?
How can i forbid a.first = "c" for example ?
推荐答案
您可以覆盖 __ setattr __
以防止任何更改:
You can override __setattr__
to either prevent any changes:
def __setattr__(self, name, value):
raise AttributeError('''Can't set attribute "{0}"'''.format(name))
或阻止添加新属性:
def __setattr__(self, name, value):
if not hasattr(self, name):
raise AttributeError('''Can't set attribute "{0}"'''.format(name))
# Or whatever the base class is, if not object.
# You can use super(), if appropriate.
object.__setattr__(self, name, value)
$ c> hasattr 对允许的属性列表进行检查:
You can also replace hasattr
with a check against a list of allowed attributes:
if name not in list_of_allowed_attributes_to_change:
raise AttributeError('''Can't set attribute "{0}"'''.format(name))
另一种方法是使用属性而不是纯属性:
Another approach is to use properties instead of plain attributes:
class A(object):
def __init__(self, first, second):
self._first = first
self._second = second
@property
def first(self):
return self._first
@property
def second(self):
return self._second
这篇关于如何使类不可变在python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文