gpt4 book ai didi

python - 如何使我的 Python `set` 和 `frozenset` 子类在进行二进制运算时保留其类型?

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

我有一些 setfrozenset 子类,分别是 OCDSetOCDFrozenSet。当我在二进制操作中将它们与其祖先类的实例一起使用时,祖先类主导结果的类型 - 我的意思是,当我执行从 中减去 OCDFrozenSet 之类的操作时freezeset,我得到一个 frozenset…但是如果我反转操作中的类型(即从 OCDFrozenSet< 中减去 frozenset),情况也是如此。/.

像这样:

enter image description here

...对我来说特别违反直觉的烦恼是使用 -= (就地减法)会改变现有实例的类型!

我对如何处理此类事情的了解严格来自 C++,其中操作的类型是在(可能是模板化的)运算符重载函数中显式指定的既定结论;在 Python 中,类型系统通常更加隐式,但它并不像我现在所相信的就地操作那样难以预测。

那么,解决这个问题最方便的方法是什么——我认为它涉及重写感兴趣的子类中的一些双下划线实例方法?

最佳答案

就地操作并不保证它们会就地更新对象,它完全取决于对象的类型。

Tuple、frozenset 等是不可变类型,因此不可能就地更新它们。

来自library reference关于就地运算符:

For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable.

类似地,frozenset 文档也提到了同样的事情 about in-place operations [source ]:

The following table lists operations available for set that do not apply to immutable instances of frozenset.

<小时/>

现在,由于您的 OCDFrozenSet 未实现 __isub__,它将回退到 __sub__ 方法,该方法将返回基类的类型卡住集。使用基类是因为 Python 不知道基类在 __sub__ 操作中新创建的 frozenset 上期望的参数。

更重要的是,这是一个 bug in Python 2如果此类操作返回子类实例,则修复仅 ported to Python 3但为了防止破坏现有系统。

<小时/>

要获得预期的输出,您可以在子类中提供所需的方法:

class OCDFrozenSet(frozenset):
def __sub__(self, other):
return type(self)(super().__sub__(other))

def __rsub__(self, other):
return type(self)(super().__rsub__(other))

关于python - 如何使我的 Python `set` 和 `frozenset` 子类在进行二进制运算时保留其类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52834400/

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