如何在子类中覆盖在其父类中使用的属性?

2024-05-23 10:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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())

如何从class ElectricCar(Car)中删除属性year? 我希望属性year仍在父类class Car()中,但要从子类中删除


Tags: tonameselfgetmakemodelinitdef
1条回答
网友
1楼 · 发布于 2024-05-23 10:23:45

是的,你可以,但这样做是不对的。如果year不应在ElectricCar中使用,则它必须位于另一个类或对象中的某个位置。在父级中放置某些内容,然后在子级中删除它是不对的。但是顺便说一下,你可以这样做:

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.

相关问题 更多 >

    热门问题