Python __len__() Method
The __len__() Method
The __len__() method controls what the built-in len() function returns for your object.
Example
Return the number of employees in a Company:
class Company:
def __init__(self, employees):
self.employees = employees
def __len__(self):
return len(self.employees)
c1 = Company(["Emil", "Tobias", "Linus"])
print(len(c1))
Try it Yourself »
Note: Without __len__(), calling len(c1) would raise a TypeError, since Python would not know what "length" means for a Company.