1. 程式人生 > >python中新式類和經典類

python中新式類和經典類

代碼執行 bsp 對象 init super 多重 需要 默認 結果

python中的類分為新式類和經典類,具體有什麽區別呢?簡單的說,

1.新式類都從object繼承,經典類不需要。

  Python 2.x中默認都是經典類,只有顯式繼承了object才是新式類

  Python 3.x中默認都是新式類,不必顯式的繼承object

2.經典類繼承深度優先,新式類繼承廣度優先。

  在多重繼承關系下,子類的實例對象想要調用父類的方法,向上尋找時的順序。

3.新式類相同父類只執行一次構造函數,經典類重復執行多次。

  

class A:

  def __init__(self):
    print ‘a‘,
class B(A):
  def __init__(self):
    A().__init__()
    print ‘b‘,
class C(A):
  def __init__(self):
    A().__init__()
    print ‘c‘,
class D(B,C):
  def __init__(self):
    B().__init__()
    C().__init__()
    print ‘d‘,

class E(D,A):
  def __init__(self):
    D().__init__()
    A().__init__()
    print  ‘e‘,
d=D()
print ‘‘
e=E()

  

代碼執行後打印如下:

a a b a a b a a c a a c d
a a b a a b a a c a a c d a a b a a b a a c a a c d a a e

第一行應該按如下分組a a b 、a a b |a a c 、a a c| d。首先執行D的init函數,D的init包含B和C的init,都執行之後才會執行print d,至於為什麽顯示執行了兩次構造函數,這個取決於類內部的call方法,之後介紹。

class A(object):
  def __init__(self):
    print ‘a‘,
class B(A):
  def __init__(self):
    super(B,self).__init__()
    print ‘b‘,
class C(A):
  def __init__(self):
    super(C,self).__init__()
    print ‘c‘,
class D(B,C):
  def __init__(self):
    super(D,self).__init__()
    print ‘d‘,
class E(D,A):
  def __init__(self):
    super(E,self).__init__()
    print  ‘e‘,
d=D()
print ‘‘
e=E()

  

結果打印如下:

a c b d
a c b d e

python中新式類和經典類