空的用户定义数据对象的真值

问题描述 投票:0回答:1

这更多的是一个哲学问题。

在 Python 中,

bool([])
的计算结果为
False
。 另一方面,请考虑以下因素:

from dataclasses import dataclass


@dataclass
class Lists:
    items: list[str]
    other_items: list[str]


assert bool(Lists(items=[], other_items=[]))

上面的代码片段不会引发

AssertionError

这是为什么?

我遇到了一个用例,通过聚合对象属性的真值来推断对象的真值似乎是有意义的。

这样做之前有什么注意事项需要记住吗?

(我说的是数据类,例如

dataclass
pydantic.BaseModel

python boolean pydantic python-dataclasses
1个回答
0
投票

Python 类的实例总是真实的 除非它实现了 __bool__()

简单的例子:

class FOO:
  def __init__(self, x=None):
    self._x = x
  def __bool__(self) -> bool:
    return self._x is not None

class BAR:
  def __init__(self, x=None):
    self._x = x

print(bool(FOO()))
print(bool(FOO(1)))
print(bool(BAR()))
print(bool(BAR(1)))

输出:

False
True
True
True
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.