【发布时间】:2019-03-16 21:24:44
【问题描述】:
我正在从 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 methodsData 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")
【问题讨论】:
标签: python-3.x