布尔值有两个可能的值。是否存在有三种可能的值类型? [英] Booleans have two possible values. Are there types that have three possible values?

查看:134
本文介绍了布尔值有两个可能的值。是否存在有三种可能的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python\">What's在Python中实现一个枚举的最佳方式?


我正在写,理想情况下,我想返回三个州中的一个功能:是,否和不知道


  1. 做任何编程语言有有三个,只有三个国家一类?就像一个布尔值,但有三种状态,而不是两个?


  2. 在没有这样的类型(如Python)的语言,什么是重新present这个最有型?

    目前我想我会用一个整数( 0 无, 1 为唐去知道和 2 为是),但也许有更好的办法?整数显得有点幻数。

    我可以返回 ,但作为将评估为在大多数比较语境似乎有点成熟的错误。



解决方案

在Python中我会做到这一点与持有这三个值中的一个包装对象;我会使用。由于布尔类对象有三个可能的值隐感实性值是有问题,我们会解决,通过的驳回了完全的(加在 __非零__异常(),或在Python 3, __布尔__()),因此要求比较始终明确完成,使用 == != 。我们将实现平等的身份,以便只有特定的单值是匹配的。

 类三态(对象):
    高清__init __(自我,值=无):
       (如果有的话值为V在(真,假,无)V):
          self.value =价值
       其他:
           提高ValueError错误(三态值必须为True,False或无)    高清__eq __(自我,其他的):
       返回(self.value是other.value如果isinstance(其他三态)
               其他self.value是其他)
    高清__ne __(自我,其他的):
       返回不能自其他==
    高清__nonzero __(个体经营):#的Python 3:__bool __()
       提高类型错误(三态对象可能不被用作隐布尔)    高清__str __(个体经营):
        返回STR(self.value)
    高清__repr __(个体经营):
        回归三态(%S)%self.value

用法:

  T =联亚(真)
ŧ==真真正#
牛逼!=假#真
吨(真,假)#真
布尔(T)#异常!
如果T:打印呜#异常!

在使用三态对象时,必须明确指定哪些值匹配,即富==真或酒吧!=无。你也可以做富在(假,无)来匹配多个值(当然的两个值是相反!= 用一个数值)。如果你希望能够与这些对象执行其他逻辑操作,你可以通过重写某些操作(但不幸的是,逻辑不是实现这些的方法,或可能,是不能覆写,虽然还有的的建议补充说)。

另外请注意,不能覆盖 ID()在Python,所以如三态(无)是无;两个对象实际上不同。由于良好的Python的风格是使用针对单身人士比较时,这是不幸的,但不可避免的。

编辑16年4月27日:增加一个三态比较对象到另一个支持

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

I’m writing a function that, ideally, I’d like to return one of three states: "yes", "no", and "don’t know".

  1. Do any programming languages have a type that has three, and only three states? Like a boolean, but with three states instead of two?

  2. In languages that don’t have such a type (like Python), what’s the best type to represent this?

    Currently I think I’ll go with an integer (0 for "no", 1 for "don’t know" and 2 for "yes"), but maybe there’s a better way? Integers seem a bit "magic number".

    I could return True, False or None, but as None would evaluate to False in most comparison contexts it seems a bit ripe for errors.

解决方案

In Python I'd do that with a wrapper object that holds one of those three values; I'd use True, False, and None. Since the implicit truthiness value of a Boolean-like object with three possible values is problematic, we'll solve that by disallowing that entirely (raising an exception in __nonzero__(), or in Python 3, __bool__()), thus requiring that comparisons always be done explicitly, using in, ==, or !=. We'll implement equality as identity so that only the specific singleton values True, False, and None are matched.

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 implicit Boolean")

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

Usage:

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

When using Tristate objects, you must explicitly specify which values to match, i.e. foo == True or bar != None. You can also do foo in (False, None) to match multiple values (though of course in two values is the opposite of != with a single value). If there are other logic operations you wish to be able to perform with these objects, you could implement these as methods, or possibly by overriding certain operators (sadly, however, logical not, and, and or are not overrideable, though there's a proposal to add that).

Also note that you can't override id() in Python, so e.g. Tristate(None) is None is False; the two objects are in fact different. Since good Python style is to use is when comparing against singletons, this is unfortunate, but unavoidable.

Edit 4/27/16: Added support for comparing one Tristate object to another.

这篇关于布尔值有两个可能的值。是否存在有三种可能的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆