定义抽象基类(Abstract Base Classes)
博客专区 > _Change_ 的博客 > 博客详情
定义抽象基类(Abstract Base Classes)
_Change_ 发表于10个月前
定义抽象基类(Abstract Base Classes)
  • 发表于 10个月前
  • 阅读 1
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

摘要: 抽象基类一般用于规定子类必须重新定义某些方法

比如 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
共有 人打赏支持
粉丝 11
博文 82
码字总数 36478
×
_Change_
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: