我创建了一个python代码,其中Apple是父类,Macbook是子类,我不能从mackbookpro实例中调用background()函数,如下所述。AttributeError: ‘Macbook’ object has no attribute ‘year_established’.
如果我声明 成立年份 不在 __init__
函数工作正常。
为什么我不能在子组件实例中获取父类构造函数中提到的数据?
class Apple:
# year_established=1976 --code run successfully if I declare value here
# -- but I commented out
def __init__(self):
self.year_established=1976
def background(self):
return ('it is established in {}'.format(self.year_established))
class Macbook(Apple):
def __init__(self):
self.price = 10000
def productdetails(self):
return (str(self.price) + self.background())
macbookpro = Macbook()
print(macbookpro.productdetails())
解决方案:
你需要将父类的初始化器调用到子类的初始化器中,就像…一样。
class Apple:
def __init__(self):
self.year_established = 1976
def background(self):
return ('it is established in {}'.format(self.year_established))
class Macbook(Apple):
def __init__(self):
super().__init__()
self.price = 10000
def productdetails(self):
return (str(self.price) + self.background())
macbookpro = Macbook()
print(macbookpro.productdetails())