好比 web 框架中的 cache 部分的基類通常相似下面這樣:python
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)
三種定義抽象基類的方法web
一、使用 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
二、使用 NotImplementedError 異常ide
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
三、使用 abc 模塊code
*python2ip
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
*python3get
from abc import ABCMeta, abstractmethod class BaseClass(metaclass=ABCMeta): @abstractmethod def action(self, foobar): pass
推薦使用 abc 模塊,NotImplementedError 也比較經常使用。input
example:it
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