2

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()      
1
  • 1
    You're calling second as a class method. If you want to call it with a class rather than a class instance, then make it a @classmethod. For third, if it doesn't need a class or a class instance, then make it a @staticmethod. Commented May 24, 2019 at 1:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The only thing you're missing out is that you're not creating an instance for your class.

Try this-

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

    def second(self):
        print('inst method 1')
        self.third(self)

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

instance = A()
instance.first()   

This should give you your desired output. As for why the last method needs self as a parameter, self refers to the instance that you're applying the method on, and thus you can change it's properties with it. Let me give you an example-

class Kid():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def change_age(self, age):
        self.age = age

tom = Kid('Tom', 13)
print(tom.age) #prints 13
tom.change_age(14)
print(tom.age) #prints 14

Here, with the self argument in the method, Python would know which instances' property age does it have to change. In your use case, it might seem not to make much sense though. I hope this helps. :)

Comments

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.