让Python布尔值打印为'开'或'关'而不是'True'或'False
有没有什么好的方法可以创建一个变量,它的功能和布尔值(也就是真或假)一样,但显示的时候是On
或Off
,而不是True
或False
?现在程序打印的是:Color: True
,但如果打印Color: On
会更合适。
顺便说一下,我最开始尝试创建一个叫OnOff
的类,让它继承自bool
:
class OnOff(bool):
def __str__(self):
if self: return 'On'
else: return 'Off'
从评论中我了解到,bool
是一个单例,这就是我失败的原因:
Traceback (most recent call last):
class OnOff(bool):
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
12 个回答
7
我最喜欢的一个小技巧是用布尔值来索引数组:
return "Color: {0}".format(['Off','On'][has_color])
需要注意的是,布尔值的值必须是 False
、True
、0
或 1
。如果你有其他的值,就需要先把它转换成布尔值。
10
def Color(object):
def __init__(self, color_value=False):
self.color_value = color_value
def __str__(self):
if self.color_value:
return 'On'
else:
return 'Off'
def __cmp__(self, other):
return self.color_value.__cmp__(other.color_value)
虽然这可能对你来说有点过了。:)
19
这段代码 print ("Off", "On")[value]
也能正常工作,因为在 Python 里,(False, True)
和 (0, 1)
是等价的。