python中super方法的注意點

2021-08-21 19:29:38 字數 1509 閱讀 9018

之前,碰到乙個很有意思的問題,呼叫super之後,並沒有按照預期執行。大概是如下的:

#!/usr/bin/env python

# -*- coding=utf-8 -*-

class

a(object):

def__init__

(self):

print(type(self).mro())

deftest

(self):

print('a.test')

print(id(self))

print('a.test.end')

class

b(a):

deftest

(self):

print('b.test')

print(id(self))

super(b, self).test()

print('b.test.end')

class

c(a):

deftest

(self):

print('c.test')

print(id(self))

super(c, self).test()

print('c.test.end')

class

d(b, c):

deftest

(self):

print('d.test')

print(id(self))

super(d, self).test()

print('d.test.end')

d().test()

執行結果如下:

[, '__main__.b'>, '__main__.c'>, '__main__.a'>, 'object'>]

d.test

4358651520

b.test

4358651520

c.test

4358651520

a.test

4358651520

a.test.end

c.test.end

b.test.end

d.test.end

可以看出,super的執行的順序是dstart->bstart->cstart->astart->aend->cend->bend>dend,這個順序與d的mro順序一致。

這是由於super的實現導致的,其原理如下:

def

super

(cls, inst):

mro = inst.__class__.mro()

return mro[mro.index(cls) + 1]

super會在inst的mro中查詢到匹配到cls的下乙個類,因此,從結果中也可以看到,super(x,self)中的self是同乙個例項,因此,呼叫super時會按照mro的順序執行下去。

這個點,可以作為面試題,考一下。實際工作中應該會遇到。

Python中super 方法的使用

如果在子類中也定義了構造器,既 init 函式,那麼基類的構造器該如何呼叫呢?方法 一 明確指定 使用乙個子類的例項去呼叫基類的構造器,在子類的構造器中明確的指明呼叫基類的構造器。class c p def init self p.init self print calling cs constru...

Python中super 方法的使用

先看一段 class stmatrix object 定義乙個類 docstring for stmatrix def init self,data,timestamps,t 24,checkcomplete true 建構函式 super stmatrix,self init super表繼承,這...

python中super 方法的理解

python中物件方法的定義很怪異,第乙個引數一般都命名為self 相當於其它語言的this 用於傳遞物件本身,有時候還會有乙個引數cls 相當於類名,當直接呼叫類方法的時候使用 python2中super 的用法 super class,self init python3中super 的用法 su...