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

≯℡__Kan透↙ 提交于 2020-07-15 16:01:24

问题


In python 3.9, dictionaries gained combine | and update |= operators. Is there a dunder/magic method which will enable this to be used for other classes? I've tried looking in the python source but found it a bit bewildering.


回答1:


Yes, | and |= correspond to __or__ and __ior__.

Don't look at the python source code, look at the documentation. In particular, the data model.

See here

And note, this isn't specific to python 3.9.




回答2:


Yes, the method for | is __or__ and the method for |= is __ior__. You can see an (approximate) Python implementation here in PEP 584.

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



回答3:


No need to dig through the source. It's clearly documented as __or__ and __ior__. https://docs.python.org/3/reference/datamodel.html is the relevant documentation.



来源:https://stackoverflow.com/questions/62375432/is-there-a-dunder-method-corresponding-to-pipe-equal-update-for-dicts-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!