How to access __len__() hook method inside of python class?

Question:

I’ve googled, but I couldn’t find a solution to this. And I’m not even sure if this is "a Pythonic way to do it".

Let’s take a simple example:

class Simple():
    def __init__(self):
        self.my_data = [1, 2, 3]
    
    def __len__(self):
        return len(self.my_data)

    def new_method(self):
        pass
        # -> How to access the __len__() method here

How can I access the len() method in new_method (inside the class)?

Asked By: Al-Baraa El-Hag

||

Answers:

You can call len() with an instance of Simple as parameter

s = Simple()
print(len(s)) # 3

Inside the class you can use self as the instance

def new_method(self):
    print(len(self))
Answered By: Guy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.