ITPub博客

首页 > IT职业 > IT图书 > python dict实现的魔法方法

python dict实现的魔法方法

IT图书 作者:suliver 时间:2021-09-11 09:54:51 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电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2370/viewspace-2829874/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-30

  • 博文量
    138
  • 访问量
    9094