【问题标题】:Why does the error say Object has no attribute? [duplicate]为什么错误说 Object has no attribute? [复制]
【发布时间】:2019-10-24 07:56:10
【问题描述】:

我已经多次查看此代码,但我无法找出为什么错误一直在说

    print("This car has a " + str(self.battery_size) + "-kWh battery.")
AttributeError: 'Electric' object has no attribute 'battery_size'
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year) +' '+self.make.title()+' ' + self.model.title()
        return long_name.title()

    def read_odometer(self):
        print("the car ran " + str(self.odometer_reading) + " miles ")

    def update_odometer(self, milage):
        self.odometer_reading += milage
        print("odo meter reading is "+str(self.odometer_reading))

class Electric(Car):
    def _init_(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = 70

    def describe_battery(self):
        print("This car has a " + str(self.battery_size) + "-kWh battery.")

my_tesla = Electric('tesla', 'model s', '2016')
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

任何帮助将不胜感激。 谢谢

【问题讨论】:

    标签: python class inheritance


    【解决方案1】:

    应该是:

    class Electric(Car):
        def __init__(self, make, model, year):
    

    两个下划线。

    【讨论】:

    • @InderjeetSingh 如果构造函数未正确命名为__init__,则在构造过程中不会执行。修复名称,将导致构造函数被正确调用,因此battery_size 属性将被正确分配,并且在您调用.describe_battery() 时可用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-05-26
    • 2021-03-13
    • 1970-01-01
    • 2022-01-17
    • 2022-12-03
    相关资源
    最近更新 更多