定义抽象基类(Abstract Base Classes)

比如 web 框架中的 cache 部分的基类一般类似下面这样:

class BaseCache(object):
    def get(self, key):
        raise NotImplementedError('subclasses of BaseCache must provide a get() method')

    def set(self, key, value, timeout=60):
        raise NotImplementedError('subclasses of BaseCache must provide a set() method')


class MemcachedCache(BaseCache):
    def get(self, key):
        value = self._cache.get(key)
        return value

    def set(self, key, value, timeout=60):
        self._cache.set(key, value, timeout)

三种定义抽象基类的方法

1、使用 assert 语句

class BaseClass(object):
    def action(self, foobar):
        assert False, 'subclasses of BaseClass must provide an action() method'

In [6]: BaseClass().action('a')
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-6-69f195c0ee1f> in <module>()
----> 1 BaseClass().action('a')

<ipython-input-3-25c84a2cb72e> in action(self, foobar)
      1 class BaseClass(object):
      2     def action(self, foobar):
----> 3         assert False, 'subclasses of BaseClass must provide an action() method'

AssertionError: subclasses of BaseClass must provide an action() method

2、使用 NotImplementedError 异常

class BaseClass(object):
    def action(self, foobar):
        raise NotImplementedError('subclasses of BaseClass must provide an action() method')

In [8]: BaseClass().action('a')
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-8-69f195c0ee1f> in <module>()
----> 1 BaseClass().action('a')

<ipython-input-7-81782a1e8377> in action(self, foobar)
      1 class BaseClass(object):
      2     def action(self, foobar):
----> 3         raise NotImplementedError('subclasses of BaseClass must provide an action() method')

NotImplementedError: subclasses of BaseClass must provide an action() method

3、使用 abc 模块

*python2

from abc import ABCMeta, abstractmethod

class BaseClass(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def action(self, foobar):
        pass

In [11]: BaseClass().action('a')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-69f195c0ee1f> in <module>()
----> 1 BaseClass().action('a')

TypeError: Can't instantiate abstract class BaseClass with abstract methods action

*python3

from abc import ABCMeta, abstractmethod

class BaseClass(metaclass=ABCMeta):
    @abstractmethod
    def action(self, foobar):
        pass

推荐使用 abc 模块,NotImplementedError 也比较常用。

example:


class TestBase(object):
    def get_error(self):
        raise NotImplementedError

    def do(self):
        return self.get_error()


class Duo(TestBase):
    def __init__(self):
        super(Duo, self).__init__()

    def get_error(self):
        return "Do Here"


handler = Duo()

print handler.do()


# result : Do Here
223916_bL9y_2663968.jpg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值