如何在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")
巴吉什·杜德迪亚

这是你想要的吗?
您的代码中几乎没有 udpates: 函数model_name()预计会打印model_name分配给汽车的信息,并且与carmodel的父类一样cartype,模型信息需要传递给父类并将其存储在self. 因此cartype使用type初始化model并将其传递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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章