I am having difficulties understanig inheritance in Python, but I have an idea how it works because of my somewhat larger experience in Java... To be clear, I searched the questiones here as well as online documentation, so I am aware this will be branded as repeated question in an instant :P
My code on Codecademy passes like this:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
return "This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
But as far as I can see, I'm almost defining a new class... Where is the inheritance in that? Could I do something like:
class ElectricCar(Car):
def __init__(self, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
Maybe something with a keyword
super
?
You can call the Car init method and pass its arguments
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
Car.__init__(self,model,color,mpg)
self.battery_type = battery_type
Or you can also use the super
method which is a preferred approach as mentioned in the comments.
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super(ElectricCar,self).__init__(model, color, mpg)
self.battery_type = battery_type
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