代码之家  ›  专栏  ›  技术社区  ›  Zaz Volodymyr Null

使Python bool打印为“开”或“关”,而不是“真”或“假”

  •  5
  • Zaz Volodymyr Null  · 技术社区  · 14 年前

    什么是最好的方法,使一个变量的工作完全像一个布尔,但打印 On Off 而不是 True False ? 当前程序正在打印: Color: True Color: On 会更有意义。

    OnOff 继承自的类 bool

    class OnOff(bool):
        def __str__(self):
            if self: return 'On'
            else: return 'Off'
    

    从评论中,我现在明白了 布尔 是独生子女,这就是为什么这次失败的原因:

    Traceback (most recent call last):
        class OnOff(bool):
    TypeError: Error when calling the metaclass bases
        type 'bool' is not an acceptable base type
    
    12 回复  |  直到 14 年前
        1
  •  19
  •   Jochen Ritzel    14 年前

    print ("Off", "On")[value] 也行(因为 (False, True) == (0,1) )

        2
  •  10
  •   Rahul    14 年前
    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)
    

    尽管这对你来说可能太过分了。:)

        3
  •  6
  •   Mike DeSimone    14 年前

    我最喜欢的技巧是使用bool索引数组:

    return "Color: {0}".format(['Off','On'][has_color])
    

    False , True , 0 ,或 1

        4
  •  4
  •   Tim Pietzcker    14 年前
    print "On" if color else "Off"    # Python 2.x
    print ("On" if color else "Off")  # Python 3.x
    
        5
  •  3
  •   Winston Ewert    14 年前

    您不能重载逻辑和/或操作,这将阻止您创建真正类似bool的对象。它会不断地恢复到python的bool。

    所以:不要。

    如果您不想将值打印为True和False,请不要直接调用print。打印是为了快速和肮脏的输出。如果你想要比它给你更多的东西,那么你需要做更多的工作。在这种情况下,您只需要使用ToOnOff函数。

        6
  •  1
  •   Community CDub    7 年前

    Rahul's code :

    class OnOff(object):
        def __init__(self, value):
            self._value = value
    
        def __str__(self):
           if self._value: return 'On'
           else: return 'Off'
    
        def __cmp__(self, other):
            return self._value.__cmp__(other)
    

    __cmp__ 函数使对象能够与bools进行比较,还更改了其他一些次要内容。全额贷记 Rahul .

        7
  •  0
  •   Rafael Sierra    14 年前
    mybool = {True: 'On', False: 'Off'}
    mybool[True] == 'On'
    mybool[False] == 'Off'
    
        8
  •  0
  •   liori    14 年前

    如果你不想惹麻烦的话 print

    class BoolHack(object):
        def __init__(self):
            from sys import stdout
            self.realout = stdout
    
        def write(self, text):
            if text == 'False':
                text = 'Off'
            elif text == 'True':
                text = 'On'
            self.realout.write(text)
    
    import sys
    
    sys.stdout = BoolHack()
    
    print "Hello world" # ==> Hello world
    print 1             # ==> 1
    print True, 10      # ==> On 10
    print False         # ==> Off
    print "True hack"   # ==> True hack
    

    警告:不要在实际生产代码中使用!这只是为了让你的答案完整。

    打印 对要打印的对象调用str(),然后才将字符串放入stdout。。。所以你不能检查对象的类型。但是将“False”或“True”作为单个字符串打印是非常罕见的,因此在非常具体的情况下,它可能会起作用。

        9
  •  0
  •   Alexander Ivanov    14 年前
    class Color:
        def __init__(self,C):
        if C==True:
            self.col='On'
        else:
            self.col='Off'
    
        def __cmp__(self,other):
            return self.col 
    
        10
  •  0
  •   neil    14 年前

    True.__str__=lambda:"On"

    不幸的是,它抱怨它是只读的。不管怎么说,这是一个非常黑客的方式去做!

        11
  •  0
  •   Paulo Scardine    14 年前

    试试这个奇怪的:

    a = True
    b = False
    print a and 'On' or 'Off'
    print b and 'On' or 'Off'
    
        12
  •  0
  •   Community CDub    7 年前

    根据公众的建议,我改变了主意,找到了比创建类更好的解决问题的方法:将菜单项转换为字符串 全班同学。允许我使用 the solution proposed by THC4k .

    Unidiff :

             menu.items=((
                 ('Play Game', True),
                 '  ',
                 'Speed: ', (speed, True),
                 '  ',
                 'Screen: ', (screen_width, True), 'x', (screen_height, True),
                 '  ',
    -            'Color: ', (color, True),
    +            'Color: ', (("Off", "On")[color], True),
                 '  ',
                 ('Exit', True)
             ))