gpt4 book ai didi

python - boolean 值有两个可能的值。是否存在具有三个可能值的类型?

转载 作者:IT老高 更新时间:2023-10-28 21:47:32 26 4
gpt4 key购买 nike

Possible Duplicate:
What's the best way to implement an 'enum' in Python?

我正在编写一个函数,理想情况下,我希望返回以下三种状态之一:"is"、“否”和“不知道”。

  1. 是否有任何编程语言的类型具有三个且只有三个状态?类似于 boolean 值,但具有三种状态而不是两种状态?

  2. 在没有这种类型的语言(如 Python)中,表示这种类型的最佳类型是什么?

    目前我想我会选择一个整数(0 表示“否”,1 表示“不知道”,2 表示"is"),但也许有更好的方法?整数似乎有点“魔数(Magic Number)”。

    我可以返回 TrueFalseNone,但因为 None 会评估为 False 在大多数比较上下文中,错误似乎有点成熟。

最佳答案

在 Python 中,我会使用包含这三个值之一的包装器对象来做到这一点;我会使用 TrueFalseNone。由于具有三个可能值的类 boolean 对象的隐含真实性值是有问题的,我们将通过完全禁止来解决这个问题(在__nonzero__()中引发异常,或在 Python 3 中,__bool__()),因此要求始终使用 in== 显式进行比较!=。我们将实现相等作为标识,以便仅匹配特定的单例值 TrueFalseNone

class Tristate(object):

def __init__(self, value=None):
if any(value is v for v in (True, False, None)):
self.value = value
else:
raise ValueError("Tristate value must be True, False, or None")

def __eq__(self, other):
return (self.value is other.value if isinstance(other, Tristate)
else self.value is other)

def __ne__(self, other):
return not self == other

def __nonzero__(self): # Python 3: __bool__()
raise TypeError("Tristate object may not be used as a Boolean")

def __str__(self):
return str(self.value)

def __repr__(self):
return "Tristate(%s)" % self.value

用法:

t = Tristate(True)
t == True # True
t != False # True
t in (True, False) # True
bool(t) # Exception!
if t: print "woo" # Exception!

使用 Tristate 对象时,您必须明确指定要匹配的值,即 foo == True 或 bar != None。您也可以执行 foo in (False, None) 来匹配多个值(当然 in 两个值与 != 相同单个值)。如果您希望能够对这些对象执行其他逻辑操作,您可以将它们实现为方法,或者可能通过覆盖某些运算符(但遗憾的是,逻辑 notandor 是不可覆盖的,尽管有 a proposal 来添加)。

另请注意,您不能在 Python 中覆盖 id(),例如Tristate(None) is None is False;这两个对象实际上是不同的。由于好的 Python 风格是在与单例比较时使用 is,这是不幸的,但也是不可避免的。

编辑 4/27/16:添加了将一个 Tristate 对象与另一个对象进行比较的支持。

关于python - boolean 值有两个可能的值。是否存在具有三个可能值的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com