Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call grandparent's `__str__` from child class in python?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading