为什么这不是天真的预期?
class Foo(object):
def __init__(self):
self.bar = 3
def __bool__(self):
return self.bar > 10
foo = Foo()
if foo:
print 'x'
else:
print 'y'
Run Code Online (Sandbox Code Playgroud)
(输出是x)
所有我想要的是bool(myInstance)返回False(并且myInstance在条件中评估为False,如if /或/和.我知道如何覆盖>,<,=)
我试过这个:
class test:
def __bool__(self):
return False
myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"
Run Code Online (Sandbox Code Playgroud)
有什么建议?
(我使用的是Python 2.6)
让我们说:
class Bar:
pass
A = Bar()
while A:
print("Foo!")
Run Code Online (Sandbox Code Playgroud)
然后调用什么操作A来确定while循环?
我尝试过,__eq__但没有做太多.
class ×3
python ×3
boolean ×2
python-2.x ×2
casting ×1
operation ×1
python-2.7 ×1
python-3.x ×1
while-loop ×1