Suppose we have 3 classes grandparent,parent and child where parent inherits from grandparent and child inherits from parent. I want to call the __str__ of grandparent in class child. How can I do it?
class grandparent:
def __init__(self):
pass
def __str__(self):
return f'grandparent'
class parent(grandparent):
def __init__(self):
pass
def __str__(self):
return f'{super().__str__()},parent'
class child(parent):
def __init__(self):
pass
def __str__(self):
return f'{super().__str__()},child'
In this case if I make an object from child class, after printing it I see :
c = child()
print(c) # prints 'grandparent,parent,child'
I want to see 'grandparent,child' by calling the grandparent’s __str__ in child class.
>Solution :
There are several ways how to achieve this.
First is to pass parent class to super method:
class child(parent):
def __init__(self):
pass
def __str__(self):
return f'{super(parent, self).__str__()},child'
In that case we don’t need to know "grandparent" class name. In case if you know the name of "grantparent" class we could use direct class name:
class child(parent):
def __init__(self):
pass
def __str__(self):
return f'{grandparent.__str__(self)},child'
Those 2 methods is the best practice, any of other approaches does not so flexible.