我无法检索仅由继承的子类创建的变量的值。 同样,在子类的初始化中更改从父类继承的变量的值也不适用。
这是父类:
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
这是子类:
class ElectricCar(Car):
def __init___(self, make, model, year):
super(ElectricCar, self).__init__(make, model, year)
self.odometer_reading = 100
self.battery_size = 70
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
def describe_battery(self):
print(self.battery_size)
现在,如果我尝试运行以下代码:
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla)
print(my_tesla.describe_battery())
我收到以下异常:
<class '__main__.ElectricCar'>:
{'make': 'tesla', 'model': 'model s', 'year': 2016, 'odometer_reading': 0}
AttributeError: 'ElectricCar' object has no attribute 'battery_size'
在父类中,我有一个奇数表读数变量,其值为0。
我从儿童班更改为100,但不适用。
另外,仅在子类中设置的变量battery_size
不会在init中创建。
出什么问题了?我想念什么?
答案 0 :(得分:0)
您的ElectricCar
类中有一个错字。您为方法__init___
定义了3个下划线而不是2个下划线,因此在创建新实例时不会调用该方法。
如果您将ElectricCar
类更改为此:
class ElectricCar(Car):
def __init__(self, make, model, year): #Note the two underscores
super(ElectricCar, self).__init__(make, model, year)
self.odometer_reading = 100
self.battery_size = 70
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
def describe_battery(self):
print(self.battery_size)
然后这将是输出:
<class '__main__.ElectricCar'>: {'make': 'tesla', 'model': 'model s', 'year': 2016,
'odometer_reading': 100, 'battery_size': 70}
70
None