【问题标题】:Python inheritance: Concatenating with super __str__Python 继承:与 super __str__ 连接
【发布时间】:2015-06-26 00:23:19
【问题描述】:

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

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

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

然而,这会产生类型错误:

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

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

【问题讨论】:

  • 这不是你的问题,但在 Python 3 中你可以只写 super(),不需要旧的 2.x 语法 super(B, self)

标签: python inheritance


【解决方案1】:

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

【讨论】:

  • 在python 2中,你需要你的父类来子类化对象。见isbullsh.it/2012/03/Class-inheritance-in-python
  • 在 Python 3 中,super().__str__() 更清晰、更短。
  • str(super()) 不是更短吗?
  • @GoswinvonBrederlow,嗯——是的。但它有效吗?没有。
【解决方案2】:

B 类应该是:

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

【讨论】:

    【解决方案3】:

    对于 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"
    

    【讨论】:

      【解决方案4】:

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

      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__()

      【讨论】:

        猜你喜欢
        • 2016-02-11
        • 1970-01-01
        • 2016-06-24
        • 2016-02-25
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多