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"
?
You need to do super(B, self).__str__()
. super
refers to the parent class; you are not calling any methods.
class B should be:
class B(A):
def __str__(self):
return super(B, self).__str__() + ' + that
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With