python---类接口技术

类接口技术

扩展只是一种同超类接口的方式。下面所展示的sPecial'ze.Py文件定义了多个类,示范了一些常用技巧。
Super
定义一个method函数以及一个delegate函数.
Inheritor
没有提供任何新的变量名,因此会获得Super中定义的一切内容。
Replacer
用自己的版本授盖Super的method.
EXtender
覆盖并回调默认method,从而定制Super的method.
Providel
实现Super的delegate方法预期的action方法。
研究这些子类来了解它们定制的共同的超类的不同途径。下面就是这个文件。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class Super:
    def method(self):
        print('in Super.method')
    def delegate(self):
        self.action()                     # 未被定义

class Inheritor(Super):
    pass

class Replacer(Super):
    def method(self):                   # 完全代替
        print("in Replacer.method")

class Extender(Super):
    def method(self):                    # 方法扩展
        print('starting Extender.method')
        Super.method(self)
        print('ending Extender.method')

class Provider(Super):
    def action(self):                       # 补充所需方法
        print('in Provider.action')

if __name__ == '__main__':
    for k in (Inheritor, Replacer, Extender):
        print("
" + k.__name__ + "...")
        k().method()

print("---Provider-----------------------")
x = Provider()
x.delegate()

运行结果:

Inheritor...
in Super.method

Replacer...
in Replacer.method

Extender...
starting Extender.method
in Super.method
ending Extender.method
---Provider-----------------------
in Provider.action
原文地址:https://www.cnblogs.com/chenlin163/p/7304871.html