Python继承:与super\uu str连接__

2024-04-20 05:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在基本实现中添加一个子类__str__实现:

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

class B(A):
    def __str__(self):
        return super(B, self) + " + that"

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

TypeError: unsupported operand type(s) for +: 'super' and 'str'

有没有办法得到str(B())返回"this + that"


Tags: self类型returnthatdeftype错误this
3条回答

你需要做super(B, self).__str__()super引用父类;您没有调用任何方法。

这是一些工作代码。你需要的是

1)子类对象,以便super按预期工作,以及

2)在连接字符串时使用__str__()

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


class B(A):

  def __str__(self):
    return super(B, self).__str__() + " + that"

print B()

注意:print B()在引擎盖下调用b.__str__()

对于python 2,正如其他人所发布的那样。

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

class B(A):
    def __str__(self):
        return super(B, self).__str__() + " + that"

对于python 3,语法被简化了。super不需要参数就可以正常工作。

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

class B(A):
    def __str__(self):
        return super().__str__() + " + that"

相关问题 更多 >