比如 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