深入理解python super

2021-08-16 19:51:31 字數 4050 閱讀 4179

我們在super(type, self)與super(type1, type2)的區別中,談到了這樣乙個問題,在python 3.6

super

(c, c)

.__init__

out[

108]

:

而在,python 2.7裡面是這樣的

>>

>

super

(c, c)

.__init__

這是因為在python 3.x中已經沒有unbound method這樣的概念了。在python 3.x中,如果物件呼叫方法的話,會返回乙個函式物件,如果你對於functionmethod的區別困惑的話,可以去閱讀python描述符使用指南。

python2.

7>>

>

print

super

.__doc__

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)

python3.

6>>

>

print

(super

.__doc__)

super()

-> same as

super

(__class__,

)super

(type)-

> unbound super

object

super

(type

, obj)

-> bound super

object

; requires isinstance

(obj,

type

)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()

.meth(arg)

this works for

class

methods too:

class

c(b)

: @classmethod

defcmeth

(cls, arg)

:super()

.cmeth(arg)

為什麼文件中說super(type, type)是乙個bound,但是我們在之前的測試中得到的是這樣的結果

>>

>

super

(c, c)

.__init__

其實原因在於,我始終忽略了乙個細節,就是文件中說的bound super object,也就是說它是乙個繫結的super物件,而不是乙個unbound method

method一樣,既然有bound super object,那麼就一定有unbound super object,根據文件上的敘述,就是通過super(type)實現unbound super object

那麼我們這樣super(c).__init__呼叫會返回什麼呢?會是unbound method嗎?有了前面的基礎,我想你這個時候應該不會輕易地下這樣的結論了。

>>

>

super

(c).__init__

object at 0x03656490

>

那麼什麼是method-warpper呢?

python 3.x,你可以將它理解為通過c實現的bound method。至於python 2.7,(+_+)?

另外,unbound super object可以通過下面這種方式轉化為bound super objectpython 2.7

>>

>

super

(c).__get__(c, c)

<

super

:<

class

'c'>

,>>

>>

>

super

(c).__get__(c, c)

<

super

:<

class

'c'>

,>>

>>

>

super

(c, c)

<

super

:<

class

'c'>

,>>

>>

>

super

(c, c)

<

super

:<

class

'c'>

,>>

如果在python 3.x的話

super

(c).__get__(c, c)

out[23]

:<

super

: __main__.c, __main__.c>

super

(c).__get__(c, c)

out[24]

:<

super

: __main__.c,

<__main__.c at 0x19b1ad02438

>>

super

(c, c)

out[25]

:<

super

: __main__.c, __main__.c>

super

(c, c)

out[26]

:<

super

: __main__.c,

<__main__.c at 0x19b1ad02438

>>

至此你應該對於super物件有乙個大概的映像了,並且你也就清楚了python描述符使用指南簡介中所說的描述符是乙個強大的通用協議,它們是屬性,方法,靜態方法,類方法和super()的工作機制

深入理解C語言 深入理解指標

關於指標,其是c語言的重點,c語言學的好壞,其實就是指標學的好壞。其實指標並不複雜,學習指標,要正確的理解指標。指標也是一種變數,占有記憶體空間,用來儲存記憶體位址 指標就是告訴編譯器,開闢4個位元組的儲存空間 32位系統 無論是幾級指標都是一樣的 p操作記憶體 在指標宣告時,號表示所宣告的變數為指...

mysql 索引深入理解 深入理解MySql的索引

為什麼索引能提高查詢速度 先從 mysql的基本儲存結構說起 mysql的基本儲存結構是頁 記錄都存在頁裡邊 各個資料頁可以組成乙個雙向鍊錶每個資料頁中的記錄又可以組成乙個單向鍊錶 每個資料頁都會為儲存在它裡邊兒的記錄生成乙個頁目錄,在通過主鍵查詢某條記錄的時候可以在頁目錄中使用二分法快速定位到對應...

深入理解C語言 深入理解指標

關於指標,其是c語言的重點,c語言學的好壞,其實就是指標學的好壞。其實指標並不複雜,學習指標,要正確的理解指標。指標也是一種變數,占有記憶體空間,用來儲存記憶體位址 指標就是告訴編譯器,開闢4個位元組的儲存空間 32位系統 無論是幾級指標都是一樣的 p操作記憶體 在指標宣告時,號表示所宣告的變數為指...