python笔记 类接口技术

类接口技术

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

class Super:
    def method(self):
        print('in Super.method')

    def delegate(self):

        try:
            self.action()  # 未被定义
        except:
            pass


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("\n" + k.__name__ + "...")
        k().method()

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

打印信息

'''
Inheritor...
in Super.method

Replacer...
in Replacer.method

Extender...
starting Extender.method
in Super.method
ending Extender.method
---Provider-----------------------
in Provider.action
has no action function
'''

参考python学习手册 694-695

猜你喜欢

转载自blog.csdn.net/Tourior/article/details/78218698