__call__ and __bool__: objects you can call, and objects that are true or false
🌍 In real life. A coffee machine set to "large, no sugar" needs only one button: press it and it uses its own settings. And a wallet is either empty or not, which is all you need to know before you go shopping.
The idea in one sentence: __call__ lets you call an object like a function, obj(x), using the settings in its fields; __bool__ decides whether the object counts as True or False in if, while and bool().
Its words:
- callable: anything you can put brackets after: functions, classes, and objects with
__call__;callable(x)asks - truthiness: whether a value counts as True (Lesson 5.4):
0,""and[]count as False - the fallback: without
__bool__, Python asks__len__and treats 0 as False; with neither, every object is True
Step by step:
vat = Tax(15)stores the rate in the objectvat(200)makes Python runvat.__call__(200), which usesself.ratebool(vat)(andif vat:) makes Python runvat.__bool__()
Watch each line become its dunder call:
Where bool() looks when there is no __bool__. A class that holds things usually has a __len__ (Lesson 24.3), and an empty container should count as False, just like an empty list. So Python falls back to __len__: 0 means False. Here Bag has only a __len__, and its bag is empty:
class Tax:
def __init__(self, rate):
self.rate = rate # percent
def __call__(self, amount):
return amount + amount * self.rate // 100
vat = Tax(15)
print(vat(200), vat(1000))
print(callable(vat), callable(5))
class Cart:
def __init__(self):
self.items = []
def __len__(self):
return len(self.items)
cart = Cart()
print("empty" if not cart else "has items")
cart.items.append("rice")
print("empty" if not cart else "has items")A callable object or a closure? Tax(15) and make_multiplier(3) from Lesson 16.5 do the same job: a function that remembers a setting. Use a closure for one small setting; use a class with __call__ when you also want to read or change the settings (vat.rate = 18), give it other methods, or print it nicely with __repr__.
Mistakes and edge cases.
__bool__must give back True or False: returning a number, even 0 or 1, is a TypeError ("bool should return bool")- calling an object without
__call__: a TypeError ("'Bag' object is not callable"), as the animation showed if obj:vsif obj is not None:: with a__len__or__bool__, an empty but real object counts as False; to ask only "is there an object?", compare with None__call__is looked up on the class: giving one object its ownobj.__call__ = …doesn't make it callable
Why give objects these powers? They let your objects slot into code written for functions or for True/False tests: a callable Tax can be passed anywhere a function is expected (like map(vat, prices)), and if cart: reads naturally once an empty cart counts as False.
Quiz
What does this print?
class Tax: def __init__(self, rate): self.rate = rate # percent def __call__(self, amount): return amount + amount * self.rate // 100 t = Tax(10) print(t(50), t(100))What does this print?
class Queue: def __init__(self): self.people = [] def __len__(self): return len(self.people) q = Queue() print(bool(q)) q.people.append("Ana") print(bool(q))What does this print?
class Box: pass print(bool(Box()), callable(Box), callable(Box()))Which
__bool__is correct for aWalletwithself.taka?- return self.taka > 0
- return self.taka
- print(self.taka > 0)
A Greeter is meant to be called like a function, as the last line does, but greeter("Ana") stops with "'Greeter' object is not callable". Which line is wrong?
class Greeter: def __init__(self, word): self.word = word def call(self, name): return self.word + ", " + name greeter = Greeter("Hi") print(greeter("Ana"))
Coding tasks
Write
class Tax(rate): calling aTaxobject with an amount returns the amount plusratepercent of it, worked out asamount + amount * rate // 100.Write
class Wallet(taka)so that a wallet counts as True only when it holds more than 0 taka, inbool(),ifandwhile.