python:抽象超类的实现

python中,如何去实现一个抽象超类?
看如下代码,实现了一个简单的超类模型。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : cat
# @date   : 2017/6/21.

class SuperClass:
    def method(self):
        print("method in super class.")

    def delegate(self):
        self.action()

    def action(self):
        assert False, 'sub must implement this action'


class Inheritor(SuperClass):
    pass


class Replacer(SuperClass):
    def method(self):
        print("method in replacer")


class Extender(SuperClass):
    def method(self):
        print('method in extender.')
        SuperClass.method(self)
        print('end in method')


class Provider(SuperClass):
    def action(self):
        print("action in provider.")


if __name__ == '__main__':
    for clazz in (Inheritor, Replacer, Extender, Provider):
        print("\t\t" + clazz.__name__ + " ...")
        clazz().method()

    x = Provider()
    x.delegate()
输出如下:
method in replacer
        Extender ...
method in extender.
method in suer class.
end in method
        Provider ...
method in suer class.
action in provider.

Process finished with exit code 0

这种方式实现了一个简单的抽象超类的模型,但是还不是真正的抽象超类。因为抽象,意味着该类不能被实例化。而上述的超类是可以被实例化的。

改进如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author : cat
# @date   : 2017/6/21.
from abc import ABCMeta, abstractmethod


class SuperClass(metaclass=ABCMeta):
    def method(self):
        print("method in super class.")

    def delegate(self):
        self.action()

    @abstractmethod
    def action(self):
        assert False, 'sub must implement this action'


class Inheritor(SuperClass):
    pass


class Replacer(SuperClass):
    def method(self):
        print("method in replacer")


class Extender(SuperClass):
    def method(self):
        print('method in extender.')
        SuperClass.method(self)
        print('end in method')


class Provider(SuperClass):
    def action(self):
        print("action in provider.")


if __name__ == '__main__':
    for clazz in (Inheritor, Replacer, Extender, Provider):
        pass
        # print("\t\t" + clazz.__name__ + " ...")
        # clazz().method()

    x = Provider()
    x.delegate()
    s = Inheritor()

输出如下:

Traceback (most recent call last):
action in provider.
  File "/Users/cat/PycharmProjects/py01/super-pack/inherit.py", line 49, in <module>
    s = Inheritor()
TypeError: Can't instantiate abstract class Inheritor with abstract methods action

通过给超类设置metaclass = ABCMeta以及,在需要让子类实现的方法上添加注解@abstractmethod即可实现抽象超类。即:让该类不能被实例化。

该类的子类上可以被实例化的,前提是,重写了超类中被@abstractmethod注解过的方法。

参考资料:《Learning Python》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值