AttributeError: 'ElectricCar' object has no attribute 'battery_size'
出现这种情况由于在“初始化父类的属性”( def _ _init_ _() )和“继承父类属性”
( super()._ _init_ _()),“init”两边都是两个下划线,电脑和书本分辨不出来,操作的时候太快了,可能有的地方遗漏了。对比一下程序代码:
1.有误的程序:
class Car:
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year): #完全看不出 init 两边各有两个下划线
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 44
# def update_reading(self, mileage):
# """将里程表读书设为指定值
# 禁止读书往回调"""
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("You can't roll back an odometer")
# self.odometer_reading = mileage
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
# def read_odometer(self):
# """打印一条汽车里程的信息"""
# print(f"The car odometer is {self.odometer_reading} mile on it!")
class ElectricCar(Car):
"""电动车独特之处"""
def _init_(self, make, model, year):
"""初始化父类的属性"""
super()._init_(make, model, year)
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size}-kw battery")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
错误处如下:
def _init_(self, make, model, year): #init 两边都为 一个下划线 “—”
"""初始化父类的属性"""
super()._init_(make, model, year) # init 两边都为 一个下划线 “—”
2.修改之后程序
class Car:
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 44
# def update_reading(self, mileage):
# """将里程表读书设为指定值
# 禁止读书往回调"""
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("You can't roll back an odometer")
# self.odometer_reading = mileage
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
# def read_odometer(self):
# """打印一条汽车里程的信息"""
# print(f"The car odometer is {self.odometer_reading} mile on it!")
class ElectricCar(Car):
"""电动车独特之处"""
def __init__(self, make, model, year): #修改之后
"""初始化父类的属性"""
super().__init__(make, model, year,) #修改之后
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size}-kw battery")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
输出结果为:
2019 Tesla Model S
This car has a 75-kw battery
Process finished with exit code 0
和大家一起进步