Python的内置bool方法__ror__的目的是什么?

use*_*189 4 python built-in built-in-types

在交互式解释器中,如果您键入以下内容,您可以看到一些非常有趣的东西:

1) help()

2) modules

3) __builtin__

在阅读输出一段时间后,我遇到了以下几行class bool:

__or__(...)
    x.__or__(y) <==> x|y
Run Code Online (Sandbox Code Playgroud)

然后是:

__ror__(...)
    x.__ror__(y) <==> y|x
Run Code Online (Sandbox Code Playgroud)

最后一种方法似乎描述了反向或.为什么这种方法存在?什么可能导致__or__(...)返回不同的东西__ror__(...)

che*_*ner 9

假设您编写自己的整数类,并希望它与内置整数一起使用.你可以定义__or__

class MyInt(int):

    def __or__(self, other):
        # Not a recommended implementation!
        return self | int(other)
Run Code Online (Sandbox Code Playgroud)

这样你就可以编写代码了

# Because this is equivalent to MyInt.__or__(MyInt(6), 7)
MyInt(6) | 7
Run Code Online (Sandbox Code Playgroud)

但是,Python不知道该怎么做

# First interpretation is int.__or__(7, MyInt(6))
7 | MyInt(6)
Run Code Online (Sandbox Code Playgroud)

因为int.__or__不知道如何使用一个实例MyInt.在这种情况下,Python交换操作数和尝试的顺序

MyInt.__ror__(MyInt(6), 7)
Run Code Online (Sandbox Code Playgroud)

也就是说,在右侧参数的类中查找魔术方法的交换版本.