如何以及在哪里正确地使用Python的uu和uuuu,uuu或uuuu,uuu反转_uu魔术方法

2024-05-16 19:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在google上查找这些方法的任何用例或示例,但找不到任何详细的解释,它们只是与其他类似方法一起列出的。实际上,我在查看github上的一些代码时遇到了这些方法,但无法理解其用法。有人能详细解释一下这些方法吗。这是github代码的链接,我在那里遇到了它们:https://github.com/msiemens/tinydb/blob/master/tinydb/queries.py


Tags: 方法代码httpsgithubmastercom示例用法
1条回答
网友
1楼 · 发布于 2024-05-16 19:36:27

魔术方法__and____or__和{}分别用于重写运算符a & ba | b和{}。也就是说,如果我们有课的话

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

那么

^{pr2}$

相当于

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)
#                                    ^

另请参见:

相关问题 更多 >