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:
python
class Company:
def __init__(self, employees):
self.employees = employees
def __len__(self):
return len(self.employees)
c1 = Company(["Emil", "Tobias", "Linus"])
print(len(c1))
Note: Without
__len__(), callinglen(c1)would raise aTypeError, since Python would not know what "length " means for aCompany.