python报错:AttributeError: 'ElectricCar' object has no attribute 'get_range'
发布网友
发布时间:2022-04-28 18:24
我来回答
共2个回答
热心网友
时间:2023-09-14 04:39
0down votefavorite
I'm a Python noob and am having some trouble with some inheritance learning. My code is throwing an attribute error.
class Battery():
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("\n" + "This car has a " + str(self.battery_size) +
'-kWh battery.')
def get_range(self):
"""Print a statement about the range based on the battery size."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = self.make + " can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represents aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize the attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make.title(), model, year)
self.battery = Battery()
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print(self.make + "'s " + "don't need a gas tank.")
my_tesla = ElectricCar('tesla', 'p90d', '2016')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
I've played around with the coding and the attributes, but I can't seem to get it to run without an error. Any guidance is greatly appreciated. Traceback (most recent call last): File "C:\Users\n\Downloads\inheritance.py", line 184, in my_tesla.battery.get_range() File "C:\Users\n\Downloads\inheritance.py", line 158, in get_range message = self.make + " can go approximately " + str(range) AttributeError: 'Battery' object has no attribute 'make'
热心网友
时间:2023-09-14 04:39
你好,get_range在class Battery中,Temp的父类是Car。get_range不在Car中,所有会报错。temp.battery.get_range() 这样就可以了