【发布时间】:2020-07-25 17:28:49
【问题描述】:
我明白为什么我为 ElectricCar 类调用 super(),以便能够调用父 Car 类定义的方法。但是为什么我不必调用 super() 来调用 Battery 类方法,例如 my_tesla.battery.describe_battery()?
我正在学习此示例的 Python Crash Course。
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()
【问题讨论】:
-
Battery没有超类。 -
@szatkus 那我一定是想错了。我会认为 Battery 会被视为 my_tesla.battery 的超类
-
这段代码中唯一的超类是
Car,因为ElectricCar继承自它。 -
一个
ElecticCar是一个Car,但有一个一个Battery。每个类都称为方法解析顺序 (MRO),它是在其继承层次结构中找到的类的线性序列。super提供了一种方法来调用 MRO 中“下一个”类的方法,具体取决于当前正在执行的方法。 -
Battery只是值my_tesla.battery的类。
标签: python