我正在覆盖 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")
最佳答案
简单地说__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")
关于python-3.x - Python - 如何声明实例何时为 True 或 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201638/