先上代码:
# coding:utf-8
class Super:
def method(self):
print("in Super.method")
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replaced(Super):
def method(self):
print("in Replaced.method")
class Extended(Super):
def method(self):
print("starting Extend.method")
Super.method(self)
print('end in Extended.method')
class Provider(Super):
def action(self):
print("in Provider.action")
if __name__ == '__main__':
for klass in (Inheritor, Replaced, Extended):
print("%s..." % klass.__name__)
klass().method()
print("\nProvicer...")
p = Provider()
# print("%s...\n" % p.__class__.__name__)
p.delegate()
运行结果
Inheritor...
in Super.method
Replaced...
in Replaced.method
Extended...
starting Extend.method
in Super.method
end in Extended.method
Provicer...
in Provider.action
Process finished with exit code 0
注意上面例子中的Proveder类是如何工作的。当通过Provider实例调用delegater()方法时,有两个独立的继承搜索会发生:
1.在最初的p.delegate的调用中,python会搜索Provider实例和它的上层的对象。
2.在Super.delegate方法中,self.action会对self以及它上层的对象启动新的独立继承搜索。因为self指的是Provider实例,在Provider子类中就会找到action方法。
像这种"填空"的代码结构一般就是OOP的软件框架。至少,从delegate方法的角度来看,这个例子中的超类有时也称作是抽象超类–也就是类的部分行为默认是由子类所提供的。