我正在从collections.abc中覆盖MutableSet,我希望能够确定其实例何时等于True / False。
我知道进行比较的神奇方法,但是我正在寻找类似检查Python提供的空集/列表的行为。
class Example():
pass
e = Example()
if e:
print("This shall work - the default of an instance is True")
# What I'd like is something similar to...
if []:
pass
else:
print("This shall be false because it's empty, there wasn't a comparison")
我已经查看了食谱:Special methods Data model-Other various websites-我似乎找不到答案了:(
我最终希望能够去
class A:
def __init__(self, value: int):
self.value = value
def __cool_equality_method__(self):
return self.value > 5
a = A(10)
b = A(3)
if a:
print("This happens")
if b:
print("This doesn't happen")
答案 0 :(得分:2)
__bool__
简单吗?
class A:
def __bool__(self):
if not getattr(self, 'trueish', None):
return False
else:
return True
a = A()
if a:
print("Hello")
a.trueish = True
if a:
print("a is True")
答案 1 :(得分:1)
您需要在您的类上实现__bool__
方法,该方法只是将您以前的__cool_equality_method__
重命名为__bool__
:
class A:
def __init__(self, value: int):
self.value = value
def __bool__(self):
return self.value > 5
a = A(10)
b = A(3)
if a:
print("This happens")
if b:
print("This doesn't happen")
"""
This happens
"""