![](/img/trans.png)
[英]Python, getting AttributeError: 'ElectricCar' object has no attribute 'battery'
[英]Python Attribute Error “Battery” object has no attribute “make” - inheritance
我是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 +“中可以走大約” + str(range)AttributeError:“電池”對象沒有屬性“ make”
品牌未在電池中定義。 您需要將make
傳遞給Battery
類:
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.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.