Why does this work even though I didn't invoke the __init__ for InsurancePolicy?

https://www.codecademy.com/courses/learn-python-3/lessons/inheritance-and-polymorphism/exercises/interfaces

class InsurancePolicy:
  def __init__(self, price_of_item):
    self.price_of_insured_item = price_of_item
class VehicleInsurance(InsurancePolicy):
  def get_rate(self):
    return .001 * self.price_of_insured_item
class HomeInsurance(InsurancePolicy):
  def get_rate(self):
    return .00005 * self.price_of_insured_item

This code works, but why can I access self.price_of_insured_item if I didn’t call the parent class’s __init__ method using super()? Do child classes automatically inherit the __init__ method of the parent’s?

1 Like

__init__ is called at the time an object for the class is instantiated. Read up some examples:

https://www.geeksforgeeks.org/init-in-python/

1 Like

Yes, it is inherited. Overriding the original method with a new def __init__ and using super() is for when you want to make some slight changes to to the instantiation.

1 Like

Oh that actually makes a lot of sense. I thought you had to use super() everytime you make a child class.

1 Like

Thankfully that’s not necessary, even the dunder methods are inherited. You can get away with an awful lot without ever using super() and you could basically rewrite __init__ as you please but super can be very very useful for small alterations; it’s one of those excellent options to avoid repeating yourself.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.