什么是使变量的行为像布尔值但打印 "On" 或 "Off" 而不是 "True" 或 "False" 的最佳方法?目前程序输出: "Color: True",而 "Color: On" 更有意义。
记录一下,我最初尝试创建一个从 "bool" 继承的 "OnOff" 类:
记录一下,我最初尝试创建一个从 "bool" 继承的 "OnOff" 类:
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