我正在练习 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] 删除。
我来说两句