什么时候必须使用super()调用超类方法?

时间:2020-07-25 17:28:49

标签: python

我理解为什么我要为ElectricCar类调用super()以便能够调用父Car类定义的方法。但是为什么我不必调用super()才能调用Battery类方法,例如my_tesla.battery.describe_battery()?

我正在学习本示例来自的Python速成课程。

from default_attributes import Car


class Battery:
    """A simple attempt to model a battery for an electric car"""

    def __init__(self, battery_size=75):
        """Initialize the batter's attributes"""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a statement describing the battery size."""
        print(f"This car has a {self.battery_size}-KWh battery.")

    def get_range(self):
        """Print a statement about the range this battery provides"""
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315

        print(f"This car can go about {range} miles on a full charge.")


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

    def __init__(self, make, model, year):
        """
        Initialize attributes of the parent class.
        Then initialize attributes specific to an electric car.
        """
        super().__init__(make, model, year)
        self.battery = Battery()

    def fill_gas_tank(self):
        # Overide parent methods by defining one with the same name.
        """Electric cars don't have gas tanks"""
        print("This car doesn't need a gas tank!")


my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

2 个答案:

答案 0 :(得分:0)

我认为您正在做的是将继承与组合混淆。这是一个很好的article两者之间的区别。每当继承一个类时,都需要调用super。每当您将一个班级(电动汽车)与另一个班级(电池)组合在一起时,您都不会这样做。有帮助吗?

答案 1 :(得分:0)

欢迎来到。

您只需要调用super来访问子类覆盖的方法(,具有相同名称的方法)。可以将超类定义且子类不重写的方法称为实例的方法(如果您将显式实例作为第一个参数提供,则称为类的方法),因为它们是继承的,但是在本地定义方法意味着在超类中的定义之前找到本地方法。

以下程序可能会解释这种混乱:

class SuperClass():
    def non_overridden(self):
        print("SuperClass non_overridden")
    def overridden(self):
        print("SuperClass overriden")

class SubClass(SuperClass):
    def overridden(self):
        print("SubClass overriden")
    def do_it_all(self):
        super().overridden()
        self.overridden()
        self.non_overridden()

sc = SubClass()
sc.do_it_all()

Python的发明者提供的正式explanation of Python's method resolution process值得一读,并且今天仍然有效。