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

Question:

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.

Asked By: Ali Murtaza

||

Answers:

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
Answered By: SystemSigma_
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.