gpt4 book ai didi

python - 在 Python 中创建不可变对象(immutable对象)

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:37 27 4
gpt4 key购买 nike

我想在 python 中创建一个像字典一样的不可变类。我在 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在评论中提到阻止访问 __dict__通过实现__getattr__ .

我已经实现了以下解决方案并且它有效

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

最佳答案

您可以将您想要在类中的唯一属性添加到插槽,如下所示

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')

__slots__ =('k')


x = Immutable(k=5)
print(x.k) # 5 as expected
x.__dict__.update({'k': 7}) # should raise error or update copy of x
print(x.a) # 7, thus object is still mutable

输出

5
Traceback (most recent call last):
File "inmutable.py", line 24, in <module>
x.__dict__.update({'k': 7}) # should raise error or update copy of x
AttributeError: 'Immutable' object has no attribute '__dict__'

关于python - 在 Python 中创建不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59735826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com