Python super初始化理解過程
阿新 • • 發佈:2018-09-03
upper 被子 function bbb 初始化 self. odin override class a
# -*- coding:utf-8 -*-<br data-filtered="filtered"> class A(object): def __init__(self, xing, gender): # !#1 self.namea = "aaa" # !#2 self.xing = xing # !#3 self.gender = gender # !#4 self.funca() def funca(self): print("function a : %s" % self.namea) class B(A): def __init__(self, xing, age): # !#5 super(B, self).__init__(xing, age) # !#6(age處應為gender) self.nameb = "bbb" # !#7 ##self.namea="ccc" # !#8 ##self.xing = xing.upper() # !#9 self.age = age # !#10 def funcb(self): print("function b : %s" % self.nameb) def funca(self): print("(override)function a : %s" % self.namea) b = B("lin", 22) # !#11 print(b.nameb) print(b.namea) print(b.xing) # !#12 print(b.age) print(b.gender) # !#13 b.funcb() b.funca()
上面程序的輸出結果為:
(override)function a : aaa bbb aaa lin 22 22 function b : bbb (override)function a : aaa
以上程序說明如果父類初始化方法中有調用了父類中定義的方法,恰好這個方法又被子類所覆蓋,則super(B, self).__init__(xing, age)調用的父類初始化方法中調用的方法將是被覆蓋後的方法。
Python super初始化理解過程