AttributeError:类型对象“BMW”没有属性“type”

问题描述 投票:0回答:2
class car:
        def __init__(self,model,year):
            self.model = model
            self.year = year


class BMW(car):
    def __init__(self,type,model,year):
        car.__init__(self,model,year)
        self.type = type

class Audi(car):
    def __init__(self,type1,model,year):
        car.__init__(self, model, year)
        self.type1 = type1

d500 = BMW('manual','500d',2020)
print(BMW.type)
print(BMW.model)
print(BMW.year)
python inheritance attributeerror
2个回答
1
投票

假设您想知道为什么会抛出错误

AttributeError: type object 'BMW' has no attribute 'type'

您正在实例化

BMW
的实例:
d500 = BMW('manual','500d',2020)
。但是,在后续行中,您指的是类本身,而不是您实例化的对象。

由于

model
year
type
是在
car
/
BMW
的构造函数中设置的,所以
BMW.type
未定义。

您需要致电:

print(d500.type)
print(d500.model)
print(d500.year)

而是为了引用您新创建的对象。


0
投票

您正在尝试从

type
打印
BMW
,但您只是将该对象设置为变量
d500
。请使用
d500
来访问属性。

d500 = BMW('manual','500d',2020)
print(d500.type)
print(d500.model)
print(d500.year)
© www.soinside.com 2019 - 2024. All rights reserved.