Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用抽象私有方法作为接口_Python_Oop_Interface - Fatal编程技术网

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
  • 将添加引号的责任留给接口的所有实现,并通过测试确保这一点。但这种方法似乎不太安全

“主要基于意见”IMHO。真的没有一个一刀切的答案…@Brunodesshuilliers一个正反两方面的答案是非常有价值的,不是吗?或者,可能有一些“永远不要做”的一些列出的方法?