Py学习  »  Python

如何在python中从子类调用祖父母的“__str__”?

Mohsen_Fatemi • 3 年前 • 1705 次点击  

假设我们有三节课 grandparent , parent 和 child 哪里 父母亲 继承自 祖父母 和 小孩 继承自 父母亲 。我想打电话给 __str__ 属于 祖父母 在课堂上 小孩 。我该怎么做?

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'

在这种情况下,如果我从 小孩 类,打印后我看到:

c = child()
print(c) # prints 'grandparent,parent,child'

我想看看 'grandparent,child' 打电话给祖父母 __str__ 在儿童课堂上。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/162500
文章 [ 4 ]  |  最新文章 3 年前