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