class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year new_car = Car('Audi', 'a4', 2019) class ElectricCar(Car): pass tesla = ElectricCar("Tesla", "Model 3", 2020) print(tesla.model) # still prints "Model 3"
When making a child class, why do you have to use __init__ and super() to inherit parent classes attributes when it works without them?
When making the ElectricCar child class, I put Car in parenthesis, and instead of using init and super(), I put pass and it still inherits Car class’s attributes.
Hi! I had this exact same question actually!
When making a child class, it inherits everything from the parent class. You would only use init and super() in a child class if you wanted to add an extra element to the child class (ElectricCar) that is not in the parent class (Car).
Yes, a child inherits everything from the parent class.
However, you are not limited to changing
__init__ and using
super() to make changes to the child class. You can define new methods that were previously not in the parent class.
Making changes to
__init__ in the child class is called method overriding and can be done to any other method that was defined inside the parent class. This will change the method in the child class, but not in the parent class.
super() allows a child class to invoke its parent’s version of a method, which is useful when you have overriden a method in the child class.
Thank you, this helped me and I understand better!