Nacka
Nacka

Reputation: 5

How to override an attribute in a child class which is used in its parent class?

class Car():
    """A simple attempt to represent a car."""

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year) + " " + self.make + " " + self.model
        return long_name.title()

class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""

    def __init__(self, make, model, year):
        """Initialize attributes of the parrent class."""

        super().__init__(make, model, year)


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())

How do I remove the attribute year from the class ElectricCar(Car)? I want the attribute year to still be in the parent class class Car(), but to be removed from the child class.

Upvotes: 0

Views: 89

Answers (1)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

Yes, you can, but this is not right to do it. if year shouldn't be used in ElectricCar then it must be somewhere in another class or object. this is not right to put something in parent and remove it in the child. but by the way, you can do it like this:

class ElectricCar(Car):

    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        del self.year

Note that removing year will raise AttributeError in get_descriptive_name. because there is no year.

Upvotes: 1

Related Questions