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

Calling an instance method without creating an instance of class in Python

I read on that instance methods can only be called by creating an instance (object) of the class. But it appears that I can call one without doing so. Check the code below:

class Test:
    def func(self): #Instance Method
        print(6)

Test.func(Test) # Here I am calling an instance method without creating an instance of class. How?

Please let me know what is happening behind the scenes.

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 :

Your code works because you feed as self argument the class itself.

Your function will work as long as you use self as class type and not as class instance, which is very bad practice.

I suggest to use staticmethods for such purposes:

class Test:

    @staticmethod
    def func():
        print(6)

Test.func()

or @classmethod:

class Test:

    @classmethod
    def func(cls):
        print(6)

Test.func()

Output:

6
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