如何以及在何处正确使用 Python 的 __and__、__or__、__invert__ 魔法方法

How and where to use Python's __and__, __or__, __invert__ magic methods properly

我在谷歌上四处寻找这些方法的任何用例或示例,但找不到任何详细解释,它们只是与其他类似方法一起列出。实际上,我正在查看 github 上的一些代码并遇到了这些方法,但无法理解其用法。有人可以提供这些方法的详细解释吗?这是我遇到的 github 代码的 link:https://github.com/msiemens/tinydb/blob/master/tinydb/queries.py

魔术方法__and____or____invert__分别用于覆盖运算符a & ba | b~a。也就是说,如果我们有一个 class

class QueryImpl(object):
    def __and__(self, other):
        return ...

然后

a = QueryImpl(...)
b = QueryImpl(...)
c = a & b

等同于

a = QueryImpl(...)
b = QueryImpl(...)
c = a.__and__(b)

这些方法在 tinydb 中被覆盖以支持此语法:

>>> db.find(where('field1').exists() & where('field2') == 5)
>>> db.find(where('field1').exists() | where('field2') == 5)
#                                    ^

另请参阅: