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

How to Access Parent class variable in Python and Call Parent Method using Child Object

我正在练习Python继承。我无法访问子 class 中的父 class 变量,也无法使用子对象调用父 class。

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 的父级,因此需要将模型信息传递给父级 class 并将其存储在 self 中。因此,使用 typemodel 初始化 cartype 并将此 model 传递给父级 class,如下面的代码所示:

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())