Python 使用抽象私有方法作为接口
假设我有一个表示某个接口的基类Python 使用抽象私有方法作为接口,python,oop,interface,Python,Oop,Interface,假设我有一个表示某个接口的基类 class Parser(object): __metaclass__ = ABCMeta @abstractmethod def _parse(self, text): """Internal interface. This is somethig a potential user must implement for his own implementation of Parser"""
class Parser(object):
__metaclass__ = ABCMeta
@abstractmethod
def _parse(self, text):
"""Internal interface. This is somethig a potential
user must implement for his own implementation of Parser"""
pass
def add_quotes(self, text):
"""some postprocessing. Say, every parser should have quotes"""
# ...
def parse(self, text):
"""External interface. Whoever uses children of Parser will
use this method"""
return self.add_quotes(self._parse(text))
对“内部”API使用私有方法(即让用户覆盖接口实现的私有方法)和对外使用的普通方法可以吗?这似乎有点奇怪。。。我看到了几种替代方法,但不知道哪一种更好:
- 使用元类通过某些后处理“包装”重写的方法。一个优点是内部和外部接口有一个单一的名称
- 具有同义名称,例如内部和外部方法的
和preparse
parse
- 将添加引号的责任留给接口的所有实现,并通过测试确保这一点。但这种方法似乎不太安全