Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call another method of the same class without an instance?

Tags:

python

I am directly calling a method on a class like this:

MyClass.action("Hello World!")

and inside the called method I need to refer to another method:

class MyClass:
    def action(data):
        print('first')
        # vvv How to perform this call?
        next_action(data)

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

Usually, I would use self to access the method and attributes but by calling the method on the class there is no instance that self could refer to. How can I still access one method from another in this case?

like image 480
Mick Avatar asked Feb 01 '26 21:02

Mick


2 Answers

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', data)

MyClass.action('Hello World!')

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', data)

instance = MyClass()
instance.action('Hello World!')
like image 163
Mark Avatar answered Feb 04 '26 10:02

Mark


You need to write using the self argument.

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

        self.next_action(data)

    def next_action(self, data):
        print('second')
like image 40
Albert Alonso Avatar answered Feb 04 '26 09:02

Albert Alonso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!