Python inheritance: combining with super __str__
I want the child class __str__
implementation to be added to the base implementation:
class A:
def __str__(self):
return "this"
class B(A):
def __str__(self):
return super(B, self) + " + that"
This, however, creates an error like:
TypeError: unsupported operand type for +: 'super' and 'str'
Is there a way to get a str(B())
return "this + that"
?
source to share
For python 2, like others 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
does not require the arguments to work correctly.
class A():
def __str__(self):
return "this"
class B(A):
def __str__(self):
return super().__str__() + " + that"
source to share
Here's some working code. You needed
1) a subclass object, so 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.
source to share