Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance: Concatenating with super __str__

I'd like to have a child class' __str__ implementation add to the base implementation:

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

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

This, however, produces a type error:

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

Is there any way to get str(B()) return "this + that"?

like image 451
rookie Avatar asked Jun 26 '15 00:06

rookie


4 Answers

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

like image 109
James Avatar answered Oct 09 '22 00:10

James


class B should be:

class B(A):
def __str__(self):
    return super(B, self).__str__() + ' + that
like image 31
Rudra Avatar answered Oct 09 '22 00:10

Rudra


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.

like image 4
Danver Braganza Avatar answered Oct 08 '22 23:10

Danver Braganza


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"
like image 4
Paul Rooney Avatar answered Oct 09 '22 01:10

Paul Rooney