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)

/home/minmin/PycharmProjects/myproject/venv/bin/python /home/minmin/PycharmProjects/myproject/mro.py
Traceback (most recent call last):
  File "/home/minmin/PycharmProjects/myproject/mro.py", line 35, in <module>
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?

Read more here: https://stackoverflow.com/questions/64372559/why-cant-the-behavior-of-len-be-changed-even-after-modifying-len-self

Content Attribution

This content was originally published by Hatte Hackked at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: