我创建了一个python代码,其中Apple是父类,Macbook是子类。我无法从mackbookpro实例调用background((函数,如下所述。获取错误:AttributeError:"Macbook"对象没有属性"year_established"。
如果我在__init__
函数外声明year_established,它就可以正常工作。
为什么我不能在子组件实例中获取父构造函数中提到的数据?
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())
使用Base-Class (or iterface) / Inherit-Class
而不是Child / Parent
,这将描述类的"所有权",如本例
class Apple:
def __init__(self, parent=None):
self.parent = parent
class Macbook(Apple):
def __init__(self, **kwargs):
super(Macbook, self).__init__(**kwargs)
macbookpro = Macbook()
macbookpro_child = Macbook(parent=macbookpro)
当一个类继承了一个基类,并且基类中已经存在一个方法时,super()
方法在python中被使用的原因是,在其他语言中,该方法不能更改,因为使用重写基类而不是忽略重复。要解决此问题,super调用原始方法,并且这可以在__init__()
中的任何点上完成,请注意,从基类中提取的任何方法都有super。(传递self需要给出哪个类是超级执行类的上下文(
破解旧的超级方法,它可以更直观一点
class Macbook(Apple):
def __init__(self):
Apple.__init__(self)
这是你的代码与一个超级
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(Macbook, self).__init__()
self.price = 10000
def product_details(self):
return str(self.price) + self.background()
macbookpro = Macbook()
print(macbookpro.product_details())