Issue
I've been playing around with OOP for a couple of days, and now I'm trying to understand how the super()
method works.
The problem I'm having is that I would like to call my __str__
function from another class and inherit the things in the superclass.
I read Python inheritance: Concatenating with super __str__ but that solution did not work.
The code I am having is this
class Taxi:
def __init__(self, drivername, onduty, cities):
self.drivername = drivername
self.onduty = onduty
self.cities = cities
def __str__(self):
return '{} {} {}'.format(self.drivername, self.onduty, self.cities)
class Type(Taxi):
def __init__(self, drivername, onduty, cities, model):
super().__init__(drivername, onduty, cities)
self.model = model
def __str__(self):
super(Taxi, self).__str__() #Tried as well with super().__str__()
return '{}'.format(self.model)
mymodel = Type('Foobar', True, 'Washington', 'Volvo')
print(mymodel)
So I want the __str__
function in the Taxi class to return the given values, and then the string class in the subclass to return the last value.
How do I do it?
Solution
You are completely ignoring the result of your call to the superclass definition of __str__
. You probably want something along the lines of
def __str__(self):
prefix = super().__str__()
return '{} {}'.format(prefix, self.model)
Calling super().__str__()
does not do anything magical. It is just another method call, so you need to treat it that way. The return value will not magically absorb itself into your method unless you make it so.
Answered By - Mad Physicist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.