python-3.x - Python - 如何声明实例何时为 True 或 False

标签 python-3.x

我正在覆盖 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/

相关文章:

python - 乘以包含 NaN 的 Pandas 系列行

python - Pytorch RuntimeError : [enforce fail at CPUAllocator. cpp :56] posix_memalign(&data, gAlignment, nbytes) == 0. 12 vs 0

python-3.x - Python 3.6 numpy reshape 可以工作,但值包含 e

python - 在嵌套列表中查找项目

excel - 未应用 OpenPyXL 文本换行

python-3.x - 引发语法错误的flask-dynamodb的示例?

python - 使用 Pandas python 35 将对象类型列转换为 float32 类型

Python 3 bytes.index : better way?

python - 如何导入变量的存储值?

python - 如何更正错误 ' AttributeError: ' dict_keys' object has no attribute 'remove' '?