python的super使用

本文講述一下super的使用:python

1:app

class A(object):
    def __init__():
        print "I'm A"
    def test(self):
        print "I'm test"

class B(A):
    def __init__():
        super(B,self).__init__()
    def test_B(self):
        super(B,self).test()
    
b=B()
b.test_B()

運行結果:code

這是簡單的調用utf-8

當調用父類比較多的時候,在調用方法是遵循MRO C3線性處理法則,源碼以下:源碼

#-*- encoding:GBK -*-# 
def mro_C3(*cls):
        print len(cls)
        if len(cls)==1:
            print "hello"
            if not cls[0].__bases__:
                print cls
                return cls
                
            else: 
                return cls+ mro_C3(*cls[0].__bases__) 
        else: 
            seqs = [list(mro_C3(C)) for C in cls ] +[list(cls)] 
            res = [] 
            while True: 
              non_empty = list(filter(None, seqs)) 
              if not non_empty: 
                  return tuple(res) 
              for seq in non_empty: 
                  candidate = seq[0] 
                  not_head = [s for s in non_empty if candidate in s[1:]] 
                  if not_head: 
                      candidate = None 
                  else: 
                      break 
              if not candidate: 
                  raise TypeError("inconsistent hierarchy, no C3 MRO is possible") 
              res.append(candidate) 
              for seq in non_empty: 
                  if seq[0] == candidate:
                      del seq[0] 
class C(object):
          pass
class A(C):     
          pass
class B(C):
          pass


mro_C3(A,B)

簡單的講述一下:it

​

#!/usr/bin/env python
#--*-- coding: utf-8 --*--
class A(object):
    def __init__(self):
        print "enter A"
        print "leave A"

        
class C(A):
    def __init__(self):
        print "enter C "
        super(C,self).__init__()
       
    def c(self):
        print "diaoyongfangfa"

class B(A):
     def __init__(self):
         print "enter B"
         super(B,self).__init__()
        
class D(B,C):
    def __init__(self):
        super(D,self).__init__()
        print "leave D"
        

b = D()
結果:enter B
enter C 
enter A
leave A
leave D
>>> 
​

在調用的時候首先mro(A)=[A,O]class

mro[B]=[B]+merge(mro(A)+[A])test

           =[B]+merge([A,O]+[A])object

遍歷執行merge操做的序列,若是一個序列的第一個元素,是其餘序列中的第一個元素,或不在其餘序列出現,則從全部執行merge操做序列中刪除這個元素,合併到當前的mro中。date

因此mro[B]=[B,A]+merge([O])=[B,A,O],同理mro[C]=[C,A,O]

mro[D]=[D]+merge(mro(B)+mro(C)+[B,C])

          =[D]+merge([B,A,O]+[C,A,O]+[B,C])

          =[D,B,C]+merge([A,O]+[A,O])

         =[D,B,C,A]+merge([O]+[O])

         =[D,B,C,A]

因此多父類的時候就遵循這個方式

相關文章
相關標籤/搜索