【问题标题】:'child class' object has no attribute 'attribute_name'“子类”对象没有属性“attribute_name”
【发布时间】:2018-11-10 12:12:17
【问题描述】:

我无法检索仅由继承的子类创建的变量的值。 此外,在子类的 init 中更改从父类继承的变量的值也不适用。

这是父类:

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'

我有一个oddmeter_reading 变量,它在父类中的值为0。 我从儿童班改为100,但它不适用。 还有,变量battery_size,只在子类中设置,在init中没有创建。

有什么问题?我错过了什么?

【问题讨论】:

  • 你写了__init__,右边有三个下划线,所以你没有“修补”构造函数。
  • @WillemVanOnsem 太好了!!!!我会更加注意打字错误。

标签: python python-3.x class attributes super


【解决方案1】:

您的ElectricCar 课程中有错字。您使用 3 个下划线而不是两个下划线定义了方法 __init___,因此在创建新实例时不会调用它。

如果您将 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

【讨论】:

  • 感谢上传完整代码。我会更加注意打字错误。
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
相关资源
最近更新 更多