1

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.

1
  • 3
    In this case Test.func("foo") or Test.func(None) would work too, the value of self is irrelevant. Commented Aug 29, 2022 at 12:36

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

11 Comments

@classmethod is better alternative than @staticmethod
Depends on the use case. Neither is necessarily "better", they're just different.
@AliMurtaza clearly you "can", based on the piece of code you posted. It "works" because of way Python works, but makes very fragile code.
@AliMurtaza, your code will work as long as you don't use self as a class instance of Test, but as a class type. Which is very bad practice.
It is how they are supposed to be used.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.