我想在python中创建一个像dictionary这样的不可变类。我在stackoverflow上找到了以下解决方案,但是这个对象的值可以通过使用__dict__.update
函数来更新。有没有办法阻止这一行动
class Immutable(object):
def __init__(self, **kwargs):
"""Sets all values once given
whatever is passed in kwargs
"""
for k, v in kwargs.items():
object.__setattr__(self, k, v)
def __setattr__(self, *args):
"""Disables setting attributes via
item.prop = val or item['prop'] = val
"""
raise TypeError('Immutable objects cannot have properties set after init')
def __delattr__(self, *args):
"""Disables deleting properties"""
raise TypeError('Immutable objects cannot have properties deleted')
x = Immutable(a=5)
print(x.a) # 5 as expected
x.__dict__.update({'a': 7}) # should raise error or update copy of x
print(x.a) # 7, thus object is still mutable
解决方案
正如DeepSpace在注释中提到的,通过实现__getattr__
来阻止对__dict__
的访问
我已经实现了下面的解决方案,并且成功了
class Immutable(object):
def __init__(self, **kwargs):
"""Sets all values once given
whatever is passed in kwargs
"""
for k, v in kwargs.items():
object.__setattr__(self, k, v)
def __getattribute__(self, item):
result = super(Immutable, self).__getattribute__(item)
if item == '__dict__':
return dict(**result)
return result
def __setattr__(self, *args):
"""Disables setting attributes via
item.prop = val or item['prop'] = val
"""
raise TypeError('Immutable objects cannot have properties set after init')
def __delattr__(self, *args):
"""Disables deleting properties"""
raise TypeError('Immutable objects cannot have properties deleted')
x = Immutable(a=5)
print(x.a) # 5
x.__dict__.update({'a': 7}) # update value on a copy of dict which has no effect
print(x.a) # 5 this time object value remain same
您可以将类中所需的唯一属性添加到插槽中,如下所示
输出
相关问题 更多 >
编程相关推荐