Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I call a method inside a class?

I’m calling my method like this:

myclass.action(data)

then inside the class I have a couple of methods:

class MyClass:
    def action(data):
        print('first')

        next_action(data)

    def next_action(data):
        print('second')

I tried using self to call next_action but I’m not sure how to obtain it at this point?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit:
This was a bit confusing because of the way it was being called. I didn’t realise that myclass was not an instance. I didn’t write this part and it was using get_class_name.

>Solution :

Based on how you are calling it, it look like you are trying to define class methods. To do that include @classmethod decorator. It will then pass the class as the first argument, which you can use to call it.

class MyClass:
    @classmethod
    def action(cls, data):
        print('first')

        cls.next_action(data)

    @classmethod
    def next_action(cls, data):
        print('second')

MyClass.action('data')

If, in fact, you are actually trying to make instance methods, then you need to call them from an instance. In that case you define the class without the classmethod decorator and call it from an instance. Python will then pass a reference to the instance as the first argument. But you need to create the instance to call it:

class MyClass:
    def action(self, data):
        print('first')

        self.next_action(data)

    def next_action(self, data):
        print('second')

instance = MyClass()
instance.action('data')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading