覆盖内置"和"

Dob*_*boy 3 python overriding

原始的"和"可以被覆盖吗?例如,如果我尝试做这样的事情

class foo():
    def __and__(self,other):
          return "bar"
Run Code Online (Sandbox Code Playgroud)

这得到输出

>> foo() and 4
4
>> foo().__and__(4)
'bar'
Run Code Online (Sandbox Code Playgroud)

我的直觉是内置并且不能被覆盖,不应该被覆盖以免引起混淆.

我想和函数不应该被改变,因为它不需要,因为它的行为就像

def and(self,other):
    if( not bool(self) ):
           return self
    else:
           return other
Run Code Online (Sandbox Code Playgroud)

Ada*_*erg 7

__and__覆盖按位运算符&,而不是逻辑运算符.

要给你的类布尔逻辑处理,定义一个__nonzero__方法:http://docs.python.org/reference/datamodel.html#object.__nonzero__