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.
callPrinty, a consumer of your classes can just callprintyon any instance ofparentor any of its children. If you need to override it in any of the children, you can. If the parent implementation also needs to be invoked, you can usesuper.self.methodis used where the child doesn't override that method,super().methodis used when it does, but you need to explicitly bypass the override (e.g. because that's the method you're in and you don't want to cause endless recursion). I don't know what you mean by "drawbacks".superoverselfis probably a bit more readable. Additionallysupercan be used to directly select which superclass method you want to access in the event of multiple-inheritance where the method name occurs more than once (assuming 'self' will just use the one that's defined first). I.e.child(p1, p2):def something(self): self.method()would usep1.methodoverp2.methodcorrect? But are there any other "gotchas" / bad in practice for not using super?childdoesn't overridemethodthen againself.methodis fine.