-
super 解決了類繼承時候,不同類的同名稱方法繼承問題
-
當執行下面代碼的時候,代碼會報錯’Girl’ object has no attribute ‘height’,
-
兩個類(Girl 和Person)有相同的方法名稱,init 和about,當名稱相同時候子類的方法會覆蓋’父類’(這個父類的叫法有問題姑且這麼叫)
-
在子類Girl中,__init__方法已經覆蓋父類的方法,
-
當執行 E.about(‘Elisabeth’) ,這個about 是子類的about ,這個方法會用到height,但是這個功能在父類中的__init__的方法裏面,不好意思被覆蓋掉了,所以報錯了
class Person:
def __init__(self):
self.height=180
def about(self,name):
print('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
class Girl(Person):
def __init__(self):
self.age=16
def about(self,name):
print('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
self.height,self.age))
if __name__=='__main__':
E=Girl()
E.about('Elisabeth')
在子類Girl裏面加上 super(Girl,self).init(),那麼父類的__init__方法下移,子類的__init__方法繼承了父類的功能
class Person:
def __init__(self):
self.height=180
def about(self,name):
print ('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
class Girl(Person):
def __init__(self):
super(Girl,self).__init__()
self.age=16
def about(self,name):
print('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
self.height,self.age))
if __name__=='__main__':
E=Girl()
E.about('Elisabeth')
可以看出現在這個方法還是Girl 裏面的,因爲子類的同名方法覆蓋父類的方法
from Girl about +++++
, Elisabeth is a hot girl ,she is about 180,and her age is 16
加載父類中的about方法
class Person:
def __init__(self):
self.height=180
def about(self,name):
print('from Person about++++{} , {} is about {}'.format('\n',name,self.height))
class Girl(Person):
def __init__(self):
super(Girl,self).__init__()
self.age=16
def about(self,name):
super(Girl,self).about(name)
print ('from Girl about +++++{} , {} is a hot girl ,she is about {},and her age is {}'.format('\n',name,
self.height,self.age))
if __name__=='__main__':
E=Girl()
E.about('Elisabeth')
from Person about++++
, Elisabeth is about 180
from Girl about +++++
, Elisabeth is a hot girl ,she is about 180,and her age is 16