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.
Python3
class GFG: def __init__( self , a): self .a = a def __len__( self ): return len ( self .a) obj = GFG( "w3wiki" ) print ( len (obj)) |
Output:
13
Example 2:
When the object doesn’t have a predefined __len__ method, then while executing the len function it gives a TypeError, but it can be corrected by defining a __len__ method by our own,
Python3
class GFG: def __init__( self , item): self .item = item def __len__( self ): return 1 obj = GFG( "w3wiki" ) print (obj.__len__()) |
Output:
1
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.
Contact Us