python Parent.__init()和super(Child, self)的區別


super函數做的事情

def supper(cls, inst):
    mro = inst.__class__.mro()
    return mro[mro.index(cls) + 1]

inst生成父類的列表

從列表中找到cls的索引,然后返回其下一個索引

假設

mro = [a,b,c]

cls = b

那么cls的索引為1

返回的是其下一個索引也就是mro[2]即c

mro 全程是Method Resolution Order

方法返回的是inst的所有的父類,

順序是

假設a是基類,b,c都是a的子類,d繼承了b和c(繼承順序是b,c)

那么d的mro返回的是

[d,b,c,a]

對d使用super(d,self)方法返回的是b

更詳細內容請參看python cookbook

http://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p07_calling_method_on_parent_class.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM