Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python basic inheritance [duplicate]

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

?

like image 561
dzenesiz Avatar asked Mar 17 '23 16:03

dzenesiz


1 Answers

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
like image 198
Daniel Avatar answered Mar 21 '23 07:03

Daniel