5

在 python 3.9 中,字典获得了组合|和更新|=运算符。是否有一种 dunder/magic 方法可以将其用于其他类?我试过查看 python 源代码,但发现它有点令人困惑。

4

3 回答 3

10

是的,|并且|=对应于__or____ior__

不看python源码,看文档。特别是数据模型。

这里

请注意,这并非特定于 python 3.9。

于 2020-06-14T16:42:58.893 回答
3

是的,|is 的方法和 is的__or__方法。你可以在 PEP 584中看到一个(近似的)Python 实现。|=__ior__

def __or__(self, other):
    if not isinstance(other, dict):
        return NotImplemented
    new = dict(self)
    new.update(other)
    return new

def __ior__(self, other):
    dict.update(self, other)
    return self
于 2020-06-14T16:44:45.333 回答
2

无需挖掘源头。它被清楚地记录为__or____ior__https://docs.python.org/3/reference/datamodel.html是相关文档。

于 2020-06-14T16:45:29.123 回答