品易云推流 关闭
文章详情页
文章 > Python基础教程 > python dict实现的魔法方法

python dict实现的魔法方法

Python dict

头像

小妮浅浅

2021-07-03 09:50:332667浏览 · 0收藏 · 0评论

方法说明

1、__or__和__ror__魔法方法对应于|操作符,__or__表示对象在操作符的左边,__ror__表示对象在操作符的右边。实现是根据左边的操作数量生成新的字典,然后将右边的操作数量更新到新的字典中,然后返回新的字典。

2、__ior__魔法方法对应|=操作符,右边的操作数量可以自己更新。

实例

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

以上就是python dict实现的魔法方法,希望对大家有所帮助。更多编程基础知识学习:python学习网

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图