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)
假设您想知道为什么会抛出错误
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)
而是为了引用您新创建的对象。
您正在尝试从
type
打印 BMW
,但您只是将该对象设置为变量 d500
。请使用 d500
来访问属性。
d500 = BMW('manual','500d',2020)
print(d500.type)
print(d500.model)
print(d500.year)