Search code examples
pythoninstanceselfclass-method

Call instance method in class method in Python


I'm designing one class for common library.

This class method called sequencially like below.

call order is 'class method' -> 'instance method' -> 'instance method'

I don't know why last instance method need self parameter..

Ordinally instance method does not need self method as we know.

What am I missing?

class A:
    @classmethod
    def first(cls):
        print('cls method')
        cls.second(cls)

    def second(self):
        print('inst method 1')
        self.third(self)  # Question! Why this method need [self] parameter?

    def third(self):
        print('inst method 2')

A.first()      

Solution

  • It's because of how you're calling second.

    Say you have such a class:

    class A:
    
        def do_thing(self):
            pass
    

    The following are equivalent:

    a = A()
    a.do_thing()
    
    A.do_thing(a)
    

    In other words, when we call a method of an instance, it is the same as looking up a function attribute of the class object and calling it with that instance as the first argument.

    Now, note that when you call second, you pass cls to it. That is the class object and not an instance, which means that you're doing something like A.do_thing. Therefore, for it to know which instance you want to call third on, you need to pass in self.