all Python 3OOPfunction
__len__
magic methods
The method len(obj) calls. It must return a non-negative integer.
Syntax
def __len__(self) -> int: ...
Besides len(), __len__ defines truthiness: an object without __bool__ is false when __len__ returns 0, which is why if container: works for your own collections too. A negative or non-integer value raises ValueError or TypeError right inside len().
Examples
class Deck:
def __init__(self, cards):
self.cards = list(cards)
def __len__(self):
return len(self.cards)
d = Deck('AKQ')
print(len(d)) # → 3
print(bool(Deck(''))) # → False — пустая колода ложна
See also
Open in the full glossarydocs.python.orgReport an inaccuracy