如何在Python中访问父类变量并使用子对象调用父方法



我正在练习Python继承。我不能在子类中访问父类变量,也不能使用子对象调用父类。

class carmodel():
def __init__(self, model):
self.model=model
def model_name(self):
print("Car Model is", self.model)

class cartype(carmodel):
def __init__(self, typ):
super().__init__(self, model)
self.typ = typ
def ctyp(self):
print(self.model, "car type is",self.typ)
car1=cartype("Sports")
car1.ctyp()
car1.model_name("Tesla Plaid")

这是你想要的吗?
你的代码很少更新:函数model_name()期望打印分配给汽车的model_name,并且由于carmodelcartype的父类,因此需要将模型信息传递给父类并存储在self中。因此,用typemodel初始化cartype,并将model传递给父类,如下面的代码所示:

class carmodel():
def __init__(self, model):
self.model=model
def model_name(self):
print("Car Model is", self.model)

class cartype(carmodel):
def __init__(self, typ, model):
super().__init__(model)
self.typ = typ
def ctyp(self):
print(self.model, "car type is",self.typ)
car1=cartype("Sports", "Tesla Plaid")
car1.ctyp()
car1.model_name()

输出:

Tesla Plaid car type is Sports
Car Model is Tesla Plaid

下面是您可能会发现有用的代码重建:-

class carmodel():
def __init__(self, model):
self.model=model
def model_name(self):
return f'Model={self.model}'

class cartype(carmodel):
def __init__(self, typ, model):
super().__init__(model)
self.typ = typ
def ctyp(self):
return f'Model={self.model}, type={self.typ}'
car=cartype("Sports", 'Plaid')
print(car.ctyp())
print(car.model_name())