In this lesson, you will learn how to make your custom objects behave like built-in containers by responding to len() and conditional if statements.
Defining Length with __len__
When you create a class that stores a collection of items, users naturally expect to use the len() function to check the size. Python allows this by implementing the __len__ magic method. This method must always return an integer representing the "size" of your object.
class ShoppingCart:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
cart = ShoppingCart(["Apple", "Banana"])
print(len(cart)) # Output: 2
Controlling Truthiness with __bool__
In Python, objects can be evaluated for their "truthiness" in conditional contexts (like if my_object:). By default, all custom objects are considered True. You can override this behavior using the __bool__ magic method, which must return either True or False.
If you don’t define __bool__, Python checks __len__ as a fallback: if __len__ returns 0, the object is False; otherwise, it is True. Defining __bool__ explicitly gives you total control:
class Inventory:
def __init__(self, stock):
self.stock = stock
def __bool__(self):
# The inventory is only "truthy" if we have items in stock
return self.stock > 0
bag = Inventory(0)
if bag:
print("Items available!")
else:
print("Empty inventory.") # This will run
By implementing these methods, you enable your objects to participate in Python's natural syntax, making your code cleaner and more intuitive for others to use. You essentially teach your class how to describe its own state—whether it holds data and whether that data is meaningful in a logical check.
Key Takeaway: Use __len__ to define your object's size for the len() function and __bool__ to explicitly determine whether your object is considered "truthy" or "falsy" in conditional expressions.