我是一个Python新手,在继承学习方面遇到了一些麻烦。我的代码抛出了一个属性错误。
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()我已经尝试了编码和属性,但我似乎不能让它运行没有一个错误。任何指导都是非常感谢的。回溯(最近一次调用):文件"C:\Users\n\Downloads\inheritance.py",第184行,在my_tesla.battery.get_range()文件"C:\Users\n\Downloads\inheritance.py",第158行,在get_range消息= self.make +“can go object”+str(范围) AttributeError:'Battery‘对象没有属性'make’
发布于 2018-03-14 04:34:31
电池中未定义make。您需要将make传递给Battery-class:
class Battery():
"""A simple attempt to model a battery for an electric car."""
def __init__(self, make, battery_size=70):
"""Initialize the battery's attributes."""
self.make = make
self.battery_size = battery_size
...
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(make.title())
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print(self.make + "'s " + "don't need a gas tank.")https://stackoverflow.com/questions/49265245
复制相似问题