Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading