What is the best way to make a variable that works exactly like a bool but prints On
or Off
rather than True
or False
? Currently the program is printing: Color: True
, whereas Color: On
would make more sense.
For the record, I initially tried to make an OnOff
class that inherits from bool
:
class OnOff(bool):
def __str__(self):
if self: return 'On'
else: return 'Off'
From the comments, I now understand that bool
is a singleton, which is why this failed miserably:
Traceback (most recent call last):
class OnOff(bool):
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
Convert bool to string: str() You can convert True and False to strings 'True' and 'False' with str() .
To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.
Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
print ("Off", "On")[value]
works too (because (False, True) == (0,1)
)
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)
Although this could be overkill for you. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With