Python继承:与super __str__连接

roo*_*kie 6 python inheritance

我想将一个子类的__str__实现添加到基本实现中:

class A:
    def __str__(self):
        return "this"

class B(A):
    def __str__(self):
        return super(B, self) + " + that"
Run Code Online (Sandbox Code Playgroud)

但是,这会产生类型错误:

TypeError:+:'super'和'str'的不支持的操作数类型

有办法获得str(B())回报"this + that"吗?

Jam*_*mes 10

你需要这样做super(B, self).__str__(). super是指父类; 你没有打电话给任何方法.

  • 在 Python 3 中,`super().__str__()` 更清晰、更短。 (5认同)