Curriculum
In Python, the __bool__ method is a special method that is used to define the boolean value of an object of a class. This method is called when the bool() function is used on an object of the class, or when the object is used in a boolean context (e.g. as a condition in an if statement or a loop). The __bool__ method should return False if the object is considered “empty” or “false”, and True otherwise.
Here’s an example of how the __bool__ method can be used in Python:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __bool__(self):
return self.x != 0 or self.y != 0
p1 = Point(1, 2)
p2 = Point(0, 0)
if p1:
print("p1 is not empty")
else:
print("p1 is empty")
if p2:
print("p2 is not empty")
else:
print("p2 is empty")
In this example, we define a Point class with two attributes: x and y. We also define a __bool__ method that returns True if the Point object has non-zero x or y values, and False otherwise.
When we create a Point object with non-zero x and y values and use it as a condition in an if statement, the __bool__ method is called and returns True. Therefore, the code inside the if statement is executed and the message “p1 is not empty” is printed.
When we create a Point object with zero x and y values and use it as a condition in an if statement, the __bool__ method is called and returns False. Therefore, the code inside the else statement is executed and the message “p2 is empty” is printed.
Note that if the __bool__ method is not defined for a class, Python will call the __len__ method (if defined) to determine the boolean value of the object. If the __len__ method returns zero, the object is considered “empty” or “false”, and the boolean value is False. Otherwise, the object is considered “non-empty” or “true”, and the boolean value is True.