在 python 3.9 中是否有对应于 |= (pipe equal/update) for dicts 的 __dunder__ 方法?

Is there a __dunder__ method corresponding to |= (pipe equal/update) for dicts in python 3.9?

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

是的,||=对应__or__ and __ior__

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

here

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

是的,|的方法是__or__|=的方法是__ior__。您可以在 PEP 584 中看到(近似)Python 实现 here

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

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