Hatte Hackked
Hatte Hackked

Reputation: 23

Why can't the behavior of len() be changed even after modifying __len__(self)?

class Worker:
    def __init__(self, pay):
        self.pay = pay

    def __len__(self):
        return "{}".format(len(str(self.pay)))

worker1 = Worker(1000)

print(worker1.__len__())
print(len(worker1))
/home/minmin/PycharmProjects/myproject/venv/bin/python /home/minmin/PycharmProjects/myproject/mro.py
4
Traceback (most recent call last):
  File "/home/minmin/PycharmProjects/myproject/mro.py", line 35, in <module>
    print(len(worker1))
TypeError: 'str' object cannot be interpreted as an integer

Process finished with exit code 1

When I print calling the dunder method (worker1.__len__()) it returns 4 in the console. But when I try to use print the len(worker1) function using the same instance (worker1) it throws an error. Why is that happening?

Upvotes: 1

Views: 46

Answers (1)

blhsing
blhsing

Reputation: 106995

The built-in function len is a wrapper function that calls the __len__ method of the given object and then validates that the returning value of the __len__ method is an integer. If you call the __len__ method directly, then no such validation is done.

In other words, you should always make sure that __len__ returns an integer to pass len's validation:

def __len__(self):
    return len(str(self.pay))

Upvotes: 5

Related Questions