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
?
3 Answers 3
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
4 Comments
super() if possible.If you're just inheriting the object class, you are correct in saying you are essentially creating a new class - it just provides a base. In fact, in Python 3.X, this isn't needed at all. Define a class like
class Car:
def __init__(self, ...)
pass
and the object inheritance goes without saying.
You're on the right track for using it. The real power of inheritance is in building off other predefined classes, such as your ElectricCar inheriting from Car, through a definition such as:
class ElectricCar(Car):
super(ElectricCar, self).__init__()
...
This gives you the functionality of the Car class without having to redefine everything.
Check out the docs on inheritance here for more detailed info.
Comments
Where is the inheritance in that?
The inheritance lies in what you can do with these classes:
>>> car = Car('Ford Prefect', 'white', 42)
>>> print(car.display_car())
This is a white Ford Prefect with 42 MPG.
>>> electric_car = ElectricCar('Tesla Model S', 'silver', None, 'lead-acid')
>>> print(electric_car.display_car())
This is a silver Tesla Model S with None MPG.
Notice that you didn't have to write the ElectricCar.display_car() method.