super與多繼承

2022-07-07 11:27:10 字數 2933 閱讀 9052

1 super

1.1 super是乙個內建類,可以參考__builtin__中的 super 類

class

super(object):

#...

def__init__(self, type1, type2=none): #

known special case of super.__init__

"""super(type, obj) -> bound super object; requires isinstance(obj, type)

super(type) -> unbound super object

super(type, type2) -> bound super object; requires issubclass(type2, type)

typical use to call a cooperative superclass method:

class c(b):

def meth(self, arg):

super(c, self).meth(arg)

# (copied from class doc)

"""pass

@staticmethod

#known case of __new__

def__new__(s, *more): #

real signature unknown; restored from __doc__

"""t.__new__(s, ...) -> a new object with type s, a subtype of t

"""pass

#....

這裡主要選取super類建立物件時候主要適用的方法 __new__ 和 __init__

__new__ 方法是建立了乙個 super 物件

__init__ 是對物件初始化, 而提供初始化的三種方式,這只說明第乙個

super(type, obj) -> bound super object; requires isinstance(obj, type) 這種方式是最常見的,將 type類 繫結在 物件 上

1.2 super的工作

super(type, obj)提供了乙個mrosuper返回mro之後類中查詢的物件

super 是從 mro 的tail進行查詢, 例如

mro:[d, c, b, a, object]

super(b, obj) 將會從 b之後查詢,即:a, object

2 多繼承

python新式類object會應用super所以先介紹super

下面多繼承示例,**自己寫,邏輯表達方式參考huanghuang

class

a(object):

defgo(self):

#第四步

#來之 c.add 中的 super

#此時的self是類d的物件d, self == d

#第五步

#列印a go

print

"go a go!

"class

b(a):

defgo(self):

#第二步

#來之 d.add 中的 super

#此時的self是類d的物件d, self == d

#self的mro:[d, b, c, a, object]

#self 會從[c, a, object]的順序查詢go方法

super(b, self).go()

#第七步

#列印b go

print

"go b go!

"class

c(a):

defgo(self):

#第三步

#來之 b.add 中的 super

#此時的self是類d的物件d, self == d

#self的mro:[d, b, c, a, object]

#self 會從[a, object]的順序查詢go方法

super(c, self).go()

#第六步

#列印c go

print

"go c go!

"class

d(b, c):

defgo(self):

#第一步

#self的mro:[d, b, c, a, object]

#self 會從[b, c, a, object]的順序查詢go方法

super(d, self).go()

#第八步

#列印d go

print

"go d go!

"print

d.mro()

d =d()

d.go()

out:

[

'__main__.d

'>,

'__main__.b

'>,

'__main__.c

'>,

'__main__.a

'>, '

object

'>]

go a go!

go c go!

go b go!

go d go!

程式執行圖

Python中多繼承與super 用法

python類分為兩種,一種叫經典類,一種叫新式類。兩種都支援多繼承。考慮一種情形,b繼承於a,c繼承於a和b,但c需要呼叫父類的init 函式時,前者會導致父類a的init 函式被呼叫2次,這是不希望看到的。而且子類要顯式地指定父類,不符合dry原則。經典類 class a def init se...

python多繼承 super問題

coding utf 8 胖子老闆的父類 class fatfather object def init self,name,args,kwargs print print 開始呼叫 fatfather print fatfather的init開始被呼叫 self.name name print 呼...

Python 多繼承中的super 與MRO

繼承 單繼承 父類 class animal object docstring for animal def init self,name self.name name def run self print is running format self.name def eat self print...