Default __len__() Implementation

When we call len(obj) from the class without defining __len__() methods then it will raise a TypeError: object of type ‘…’ has no len().

Python3




class Length:
    pass
     
obj = Length()
print(len(obj))


Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-9-c08d3a505e12> in <module>
     3 
     4 obj = Length()
----> 5 print(len(obj))
TypeError: object of type 'Length' has no len()


Python __len__() magic method

Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or equal to zero as it represents the length of the object for which it is called. 

Similar Reads

Python __len__() Function Syntax

Syntax: object.__len__() object: It is the object whose length is to be determined.                  Returns: Returns a non negative integer....

Python __len__() Function Example

When the object we are iterating already has  __len__ method defined internally, then len function gives the correct result for the object i.e....

Default __len__() Implementation

...

Contact Us