我想知道是否有办法在某些特定情况下配置一个返回False的类。是什么让空字符串和空列表返回False?如何使用我自己的条件重现该模式(例如,当该类的属性等于定义的值时返回False?)
举例说明我正在寻找的内容:
class Foo():
def__init__(self, value):
self.value=value
# I would like that the class Foo return False if his value equal 0.
a = Foo(1)
b = Foo(0)
for each in [a,b]:
if each : print( "The value isn't 0 :)" )
else : print( "The value is 0..." )
答案 0 :(得分:5)
对于Python 3,您需要__bool__
方法。对于Python 2,您需要__nonzero__
。
class Foo():
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value != 0
a = Foo(1)
b = Foo(0)
for each in [a,b]:
if each : print( "The value isn't 0 :)" )
else : print( "The value is 0..." )
答案 1 :(得分:3)
像这样实施__bool__
方法。
def __bool__(self):
return flag
# the flag is derived from the state of some attributes
# which reflects the semantics of the object being truthy / falsy