Python中如何通过子类对象访问父类变量及调用父类方法
Python继承问题修复方案
你代码里存在3个核心错误:
- 子类
cartype的构造方法没有预留model参数,无法把车型参数传递给父类完成初始化 - 调用
super().__init__时不需要手动传self,Python会自动注入,且你传入的model在子类构造作用域中未定义,会直接触发变量不存在报错 - 父类的
model_name方法定义时没有接收任何额外参数,你调用时传入"Tesla Plaid"会触发参数数量不匹配的异常
修复后的完整代码
class carmodel(): def __init__(self, model): self.model = model def model_name(self): print("Car Model is", self.model) class cartype(carmodel): # 子类构造方法新增model参数接收车型信息 def __init__(self, model, typ): # 调用父类构造时仅需要传model参数,无需手动传入self super().__init__(model) self.typ = typ def ctyp(self): print(self.model, "car type is", self.typ) # 实例化时同时传入model和typ两个参数 car1 = cartype("Tesla Plaid", "Sports") car1.ctyp() # 父类方法已经可以直接调用,model值在实例化时已经完成初始化,不需要额外传参 car1.model_name()
运行输出
Tesla Plaid car type is Sports Car Model is Tesla Plaid
内容的提问来源于stack exchange,提问作者Anil Anvesh
相关产品推荐
相关产品推荐

