[英]Inheritance in Python: What's wrong with my code?
好的,所以我正在学习继承并创建另一个类的实例,但我遇到了一个错误问题,该错误告诉我我的ElectricCar
类没有电池属性。 有人可以指出我在这里缺少什么吗? 我已经研究这个问题好几天了,但我已经无能为力了。
这是错误:
回溯(最近一次通话):文件“第 9 章 - Classes.py”,第 367 行,在 my_tesla.battery.describe_battery() AttributeError: 'ElectricCar' 对象没有属性 'battery'
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print ("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""Set the odemeter reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print ("You can't roll back an odemeter")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery_size = Battery()
def describe_battery(self):
print ("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank():
print ("This car doesn't need a gas tank!")
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print ("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print (message)
def upgrade_battery(self):
if self.battery_size == 85:
self.battery_size = 85
print ("\nYour battery size is: " + self.battery_size + " You don't need an upgrade.")
else:
self.battery_size = 85
print ("\nYour battery size has been upgraded to: " + str(self.battery_size))
my_tesla = ElectricCar('tesla', 'model s', 2016)
print (my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
问题在于,在您的ElectricCar
类中,您正在初始化Battery
类并将其设置为变量self.battery_size
而不是self.battery
。
将您的代码更改为:
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery() # NOT self.battery_size
应该让它工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.