Inheritance


#1

https://www.codecademy.com/en/courses/python-intermediate-en-egNXj/1/3?curriculum_id=4f89dab3d788890003000096

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 "+self.color+" "+self.model+" with "+str(self.mpg)+" MPG."
    
    
    def drive_car(self):
        self.condition = "used"
class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
        self.battery_type = battery_type
my_car = ElectricCar("molten salt", "BMW", "gold", 999999999999999999)
# my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition

This works, but I have question about inheritance.

So my question is about ElectricCar class wich is Car child class. Why we need to input same variables again (model, color, mpg). How come parent class can't just pass variables to child class.

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
        self.battery_type = battery_type

#2

@knezknele,

You can only get READ access up-stream in the Inheritance chain.

If the Child-class has the same property-key as the parent-class
they call it property shadowing.


#3

you need to use the super function, relate it to the parent class and specify what you are going to inherit from it:

`class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(ElectricCar, self).__init__(model, color, mpg)
        self.battery_type = battery_type`

#4

@itamarso,

If you display code-samples
could you please use some formatting....

Please re-edit your Post

  • leave one blank-line above of your code
  • select your code in the Post
  • then =click= on the </>-symbol-of-this-editor

Your code will then be in a pre-code state
and you will be able to make/present the proper indentations.

or even better use
= https://discuss.codecademy.com/t/how-do-i-format-code-in-my-posts/28351
[extra's]
https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet


#5

Thanks - Done, hope it is good - my first reply here


#6

Thank you very much for this!