class Vehicle():
def __init__(self, brand, model):
print('Am a vehicle')
def brand_name(self, brand):
print('vehicle class')
self.brand = brand
return brand
def Vehicle_model(self, model):
print('vehicle class')
self.model = model
return model
class Mazda(Vehicle):
def __init__(self, model, brand):
Vehicle.__init__(self,brand, model)
def brand_name(self, brand):
print('base class method')
self.brand = brand
print(brand +" " +'is a good brand')
def Vehicle_model(self, model):
print('base class method')
self.model = model
print('i am a '+ ' '+ self.model +''+self.brand+"model")
maz = Mazda(2019,'camry')
output>>> Am a vehicle
maz.brand_name('Toyota')
output>>> vehicle class
output>> 'Toyota'
我想重写基类中的方法,但是当我尝试使用派生类对象在派生类内部调用该方法时,它不符合我的期望。我希望派生类的方法可以执行而不是基类,请大家我在做什么错了
答案 0 :(得分:1)
在缩进后尝试代码:
class Vehicle():
def __init__(self, brand, model):
print('Am a vehicle')
def brand_name(self, brand):
print('vehicle class')
self.brand = brand
return brand
def Vehicle_model(self, model):
print('vehicle class')
self.model = model
return model
class Mazda(Vehicle):
def __init__(self, model, brand):
Vehicle.__init__(self,brand, model)
def brand_name(self, brand):
print('base class method')
self.brand = brand
print(brand +" " +'is a good brand')
def Vehicle_model(self, model):
print('base class method')
self.model = model
print('i am a '+ ' '+ self.model +''+self.brand+"model")
maz = Mazda(2019,'camry')
maz.brand_name('Toyota')
一切正常。
答案 1 :(得分:0)
Vehicle()类:
def __init__(self, brand, model):
print('Am a vehicle')
def brand_name(self, brand):
print('vehicle class')
self.brand = brand
return brand
def Vehicle_model(self, model):
print('vehicle class')
self.model = model
return model
class Mazda(Vehicle):
def __init__(self, model, brand):
Vehicle.__init__(self,brand, model) # your problem was here wrong indentation
def brand_name(self, brand):
print('base class method')
self.brand = brand
print(brand +" " +'is a good brand')
def Vehicle_model(self, model):
print('base class method')
self.model = model
print('i am a '+ ' '+ self.model +''+self.brand+"model")
做好检查缩进,这似乎是问题所在,Vehicle.__init__(self,brand, model)
缩进不好。希望对您有帮助