The built-in bool()
function will return the boolean equivalent of any argument it’s give.
Here is an example:
value = bool("This sentence is false.") print(value)
True
The boolean value of an object is used to evaluate logical expressions.
Consider this code,
if "This sentence is false": print("I don't know how I got here!")
I don't know how I got here!
The text does print out because, despite what it says, the string evaluates to True
by the if
statement. In fact, any string of non-zero length evaluates to True
and an empty string to False
.
You can define this behavior in any class you define yourself. If an object has a __bool__()
method defined, bool()
will call it to get the boolean value of the object.
For example,
class TVCharacter(): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def __bool__(self): return self.first_name == "Homer" and \ self.last_name == "Simpson" homer = TVCharacter("Homer", "Simpson") bart = TVCharacter("Bart", "Simpson") print(bool(homer)) # --> True print(bool(bart)) # --> False
True False
In the above example, the TVCharacter
class defines and implements __bool__()
to return True
for a character named “Homer Simpson” and False
for all others.
And as you can see, homer
is True
and bart
is False
.