我理解为什么要为ElectricCar类调用super(),以便能够调用由父Car类定义的方法。但是为什么我不需要调用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()发布于 2020-07-26 01:37:44
我认为你所做的是混淆了继承和组合。这里有一个关于两者之间的区别的很好的article。当你继承一个类的时候,你需要调用super.每当你将一个类(电动汽车)与另一个类(电池)组合在一起时,你就没有这样做。这有帮助吗?
发布于 2020-07-26 01:42:06
欢迎来到SO。
您只需调用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值得一读,并且在今天仍然非常有效。
https://stackoverflow.com/questions/63091381
复制相似问题