Lovethenakedgun
Lovethenakedgun

Reputation: 867

Issues with using "self" to access parent methods in Python

Within Python, I can define two classes parent and child, where the child class inherits from the parent class. Then within child I can use self and can access any methods that exist in the parent class (and presumably any other parent class in the inheritance tree) as long as the name has not been overridden in the child class.

Are there caveats to doing this? And is the recommended method just to use super()?

Code Example:

class parent:
    def add_stars(self, str):
        return '***'+str+'***'

class child(parent):
    def print_something(self):
        print(self.add_stars("Bacon"))

[In Console]
>>> c = child()
>>> c.add_stars("Wow")
'***Wow***'
>>> c.print_something()
'***Bacon***'

Edit: Going to add more clarity based on the discussion in the comments for anyone that comes across this later. What confused me was that another way of writing the above child class & getting the same functionality was to use super():

class child(parent):
    def print_something(self):
        print(super().add_stars("Bacon"))

This is the same as long as child doesn't define a method called add_stars as well. If that method does exist in child, then self will instead use the method defined in the child class, whereas super() will skip the child class and only look in superclasses. Additionally, both will use the same Method Resolution Order. What I wanted to know was, are there any issues with using self as I did in the example, when would you typically use super instead, etc?

This was answered below and in the comments.

Upvotes: 2

Views: 2989

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96277

The best way to think of super is pretend it was actually called next, as in "next in the method resolution order". In this particular case, there is no difference. Using self.some_method will try to resolve "some_method" in the current class namespace, not find it, go to the next class in the MRO, check there, find it, and it will be resolved.

If you added super, it skips the current class namespace.

In general, it is not true that the two would be equivalent. You shouldn't use super unless that is actually what you are trying to do, even in the cases where it is equivalent.

Upvotes: 2

J_H
J_H

Reputation: 20568

Are there caveats to doing this?

No, your code is fine, it correctly calls the parent function.

The current code has no need of super(). If your classes had constructors, the child constructor would have to make a call to super().

PEP8 asks that you name the classes Parent and Child, with initial capital.

You would benefit from pip install flake8 and following the advice it offers when you run flake8 *.py.

Upvotes: 0

Related Questions