Python inheritance: Concatenating with super __str__

class B should be:

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

You need to do super(B, self).__str__(). super refers to the parent class; you are not calling any methods.


Here is some working code. What you needed was to

1) subclass object, so that super works as expected, and

2) Use __str__() when concatenating your string.

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


class B(A):

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

print B()

Note: print B() calls b.__str__() under the hood.


For python 2, as other have posted.

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

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

For python 3 the syntax is simplified. super requires no arguments to work correctly.

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

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