python dict实现的魔法方法

250次阅读
没有评论

python

1、方法说明

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

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

2、实例

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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-26发表,共计516字。
新手QQ群:570568346,欢迎进群讨论 Python51学习