有没有更好的方法来定义这个布尔变量?

Is there a better way to define this boolean variable?

假设我有一些配置文件指定我是否获得 none,其中之一。也就是说,如果 get_one_of_thisTrue,那么我得到其中之一。如果它是 False,那么我得到它的 none。但是,我还想要一个布尔值来指定我得到了所有的东西,所以我将其表示为 get_all_of_this。问题是两者在某种程度上是多余的,即。如果 get_one_of_thisFalse,那么 get_all_of_this 也应该如此。有更好的方法吗?

@dataclass
class SomeConfig:
  get_one_of_this: bool
  get_all_of_this: bool

您可以结合 get_one_of_this 计算 get_all_of_this 值。

get_all_of_this = get_one_of_this and config.get_all_of_this

但是我会使用 enum 通过为 3 个状态定义一个枚举来完成它。

>>> class State(Enum):
...     NONE = 0
...     ONE = 1
...     ALL = 2
... 
>>> 

如果我是你,我会调查 enumerations。您可以枚举 none, one, all 并使用它,因为布尔值实际上只应该在存在 2 个离散状态时使用,而枚举可用于任意数量的离散状态。

class Quantity(Enum):
    NONE = 0
    ONE = 1
    ALL = 2