2016-07-24 58 views
0

我一直在寻找任何用例或这些方法的例子,但找不到任何详细的解释,他们只是沿着其他类似的方法列出。实际上,我正在浏览github上的一些代码,并且遇到了这些方法,但无法理解这些用法。有人可以提供这些方法的详细解释。这是GitHub的代码,我碰到他们的链接:https://github.com/msiemens/tinydb/blob/master/tinydb/queries.py如何以及在哪里使用Python的__and__,__or__,__invert__魔术方法正确

回答

4

的魔术方法__and____or____invert__用于覆盖运营商a & b,分别a | b~a。也就是说,如果我们有一个类

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

另请参阅:

相关问题