gpt4 book ai didi

python - __setattr__ 方法确保类中的对象不可变

转载 作者:行者123 更新时间:2023-12-01 05:15:29 24 4
gpt4 key购买 nike

我定义了以下类(其中很大一部分被缩短),但我的主要问题是,一旦用其初始化变量定义了此类的对象,我想确保这些变量在类外部是不可更改的...如果进行这样的尝试,我将需要引发 AssertionError ..我定义了 setattr 方法来引发此异常,但将此方法放入其中后会完全破坏我以前的实例和测试每当尝试创建此类的对象时,我们都会对此类进行处理,引发相同的 AssertionError...因此,这是我的类的大幅简化版本。

class Interval:
compare_mode = None

def __init__(self, min, max):
self.min = min
self.max = max

def min_max(min, max = None)-> 'Interval Object':
.
.
.
return Interval(min, max)

所有其他类方法...

def __setattr__(self, name, value):

raise AssertionError('Objects in this class are immutable')

因此,一旦我尝试测试此类中的静音对象,除了用此类中的其余方法破坏先前的测试之外,我还会遇到错误的异常。

p.min = 0;  raised wrong exception(NameError)
p.max = 0; raised wrong exception(NameError)
p.HeyImChangingYourMethodandThereIsNothingYouCanDoToStopME raised wrong exception(NameError)

最佳答案

你的问题有点难以理解——但是,在__init__中,你做了类似的事情:

self.max = 0

这将调用__setattr__,它将当场引发异常。

如果你真的想要不变性,你可以考虑使用collections.namedtuple + __slots__:

class Interval(collections.namedtuple('IntervalBase', 'min,max')):
__slots__ = ()
def method1(self):
print self.min
print self.max

作为演示:

>>> class Interval(collections.namedtuple('IntervalBase', 'min,max')):
... __slots__ = ()
... def method1(self):
... print self.min
... print self.max
...
>>> Interval(1,2)
IntervalBase(min=1, max=2)
>>> Interval(1,2).method1
<bound method Interval.method1 of IntervalBase(min=1, max=2)>
>>> Interval(1,2).method1()
1
2
>>> Interval(1,2).foo = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Interval' object has no attribute 'foo'

请注意,用户仍然可以向 Interval 的子类添加属性,但除非该子类也使用 __slots__ ...

<小时/>

另请注意,通常您不应该关心用户是否向您的实例添加附加属性。如果 API 提供的方法都无法更改(您可以通过属性强制执行),那么出于所有意图和目的,您的类是不可变的,然后您可以打开不变性提供的世界(例如合理定义的 __hash__)。

关于python - __setattr__ 方法确保类中的对象不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307437/

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