经典类和新式类:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
class P1: #(object): # parent class 1 父类 1
def foo(self):
print 'called P1-foo()'
class P2: #(object): # parent class 2 父类 2
def foo(self):
print 'called P2-foo()'
def bar(self):
print 'called P2-bar()'
class C1(P1, P2): # child 1 der. from P1, P2 #子类 1,从 P1,P2 派生
pass
class C2(P1, P2): # child 2 der. from P1, P2 #子类 2,从 P1,P2 派生
def bar(self):
print 'called C2-bar()'
class GC(C1, C2): # define grandchild class #定义子孙类
pass # derived from C1 and C2 #从 C1,C2 派生
gc = GC()
print gc.bar()
当调用foo()时,它首先在当前类(GC)中查找,如果没找到,就向上查找最亲的父类,C1.
查找未遂,就继续沿树上访到类P1,foo()被找到。
对 bar()来说,它通过搜索 GC,C1,P1 然后在 P2 中找到。因为使用这种解释顺序的缘故,
C2.bar()根本就不会被搜索了。
新式类:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
class P1(object): # parent class 1 父类 1
def foo(self):
print 'called P1-foo()'
class P2(object): # parent class 2 父类 2
def foo(self):
print 'called P2-foo()'
def bar(self):
print 'called P2-bar()'
class C1(P1, P2): # child 1 der. from P1, P2 #子类 1,从 P1,P2 派生
pass
class C2(P1, P2): # child 2 der. from P1, P2 #子类 2,从 P1,P2 派生
def bar(self):
print 'called C2-bar()'
class GC(C1, C2): # define grandchild class #定义子孙类
pass # derived from C1 and C2 #从 C1,C2 派生
gc = GC()
print gc.bar()
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a10.py
called P2-bar()
None