How do I make len() work with my class?


In this exercise the len() function is called on a list, a dictionary, and a string. How would I make len() work on a new class?


The len() function will attempt to call a method named __len__() on your class. This is one of the special methods known as a “dunder method” (for double underscore) which Python will look for to perform special operations. Implementing that method will allow the len() call to work on the class. If it is not implemented, the call to len() will fail with an AttributeError. The following code example shows a class implementing __len__().

class Bag:
    def __init__(self, item_count):
        self.item_count = item_count

    def __len__(self):
        return self.item_count

mybag = Bag(10)



Here is a fun extension of that Bag class.

class Bag:
  def __init__(self, style): = style
  def __len__(self):
    return len(

myBag1 = Bag("Gucci")
myBag2 = Bag("Canvas")
myBag3 = Bag("Target Special")

for i in (myBag1, myBag2, myBag3):
  print("I have a {} bag.".format(
  print("The length of my bag is:", len(i))

in this way can i call every built in function in python?


Why I cant return string inside len method ?

class New:
  def __init__(self, item):
    self.item = item
  def __len__(self):
    return "hello"
newObj = New(5)

Traceback (most recent call last):
  File "", line 14, in <module>
TypeError: 'str' object cannot be interpreted as an integer

1 Like


In this exercise polymorphism mean calling + operator on different class instances like List or Str or Int or float return meaningful and simply a result and not an error because in their classes something is defined (which I don’t know what it is ) that return results when we call + operator on them . in my imagination + operator call a defined method (which is same name) on each of class definitions of List or str or Int and the class definition return different results for a same + operator ====>

class List: # [element 1, element2, element3]
  def return_sum(self):
       return # append left operand with right operand  specified for list

class Str:  # "I'm String!"
   def return_sum(self):
       return # append left operand with right operand   specified for str

then calling + operator on each of these cause invoking same named methods but different results because origin is different I don't know what actually + operator works but this is what I understand how polymorphism work on high level introduced in this lesson . 

same interfaces for different classes list and str which is polymorphism ?
Is this true at all ?

Your error message actually gives you the answer:
TypeError: 'str' object cannot be interpreted as an integer

See the method description from the Python documentation (link):

object. __len__ ( self )
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0.