Search code examples
pythonmethodsinstance

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.


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