Search code examples
pythonclassinheritance

Prevent certain attributes to be inherited in child class


Need some help to solve this puzzle folks:

When creating a child class in Python and defining the init method, I would like to import all the attributes of the super/parent class except certain positional parameters and certain parameters (which are not defined inside parent classes' init method's list of positional or keyworded/non-keworded parameters but) defined within/inside the parent class init method with a default value.

Is there a way to prevent/avoid certain/specific parent class attributes to be imported in the child class upon initiation? I am aware that we can override methods in the child class which do not mimic parent class behaviors, but I am not aware how to do the same with attributes, so I was thinking if I could avoid them completely!

I will give an example of why I need a certain child class to mimic everything from its parent except certain attribute.

Consider a parent class "Car". The child class will be "ElectricCar". The parent class has an attribute defined called "liters_gasoline" with certain integer as its default value.

Now, I would like to inherit everything in the ElectricCar sub-class except that "liters_gasoline" parameter, because ElectricCars don't use fuel/gasoline. How to prevent this "liters_gasoline" parameter from being inherited in the child class? I don't want this parameter in child class!

How to do this?


Solution

  • If something inherits from a parent class it should have all the attributes of the parent class. For example "liters_gasoline" should only be in the class of a gasoline car not an electric car.