Home > Net >  How refers a method inside own parent class in Python
How refers a method inside own parent class in Python

Time:07-25

I need to force Python to call a method of the parent class completely ignoring whether or not the child classes have that method overridden.

I don't want to know if my child classes used polymorphism for that function, I just want to call the behavior of the parent class.

Example of how it would look in PHP:

<?php

class Dog {
    public function sound() {
        self::prepare();
        echo 'au au!';
    }

    public function prepare() {
        echo 'preparando parent!';
    }
}


class Boxer extends Dog {
    public function sound() {
        parent::sound();
    }

    public function prepare() {
        echo 'preparando box!';
    }
}

$boxer = new Boxer();
$boxer->sound();

The output would be:

preparando parent!
au au!

Note that I'm using SELF to tell PHP that I want the PARENT class method. If I wanted to call PREPARE from the child class, I could use $THIS and then I would have the output:

preparando box!
au au!

I wrote the following class in PYTHON:

class Dog:
    def sound(self):
        self.prepare()
        print('au au!')

    def prepare(self):
        print('preparando parent!')

class Boxer(Dog):
    def sound(self):
        super().sound()

    def prepare(self):
        print('preparando box!')

dog = Boxer();
dog.sound()

And I'm getting the following output:

preparando box!
au au!

The question is: How do I make my python class behave like PHP when I use self?

CodePudding user response:

If you want specifically to call the Dog implementation of prepare, you can use Dog.prepare(self).

class Dog:
    def sound(self):
        Dog.prepare(self)
        print('au au!')

    def prepare(self):
        print('preparando parent!')

But if you don't really want to override prepare in your subclass, maybe it would make more sense to give the methods different names.

CodePudding user response:

Based on the answers from the guys and, mainly, from @sahasrara62, I managed to make some changes and arrive at a solution:

class Dog:
    nick = 'big'

    def sound(self):
        self.prepare()
    
        print(self.nick)
        print('au au!')

    def prepare(self):
        print('preparando parent!')

class Boxer(Dog):
    def __init__(self):
        self.nick = 'little'
    
    def sound(self):
        Dog.sound(self)

    def prepare(self):
        print('preparando box!')

dog = Boxer();
dog.sound()

With the following output (preserving states, inclusive):

preparando box!
little
au au!
  • Related