python - 没有实例的类 - 更多 pythonic 方式?

标签 python python-3.x oop

我有一个应用程序,(更多的)开发人员在其中添加了命令。这些命令由一组函数组成,主要是用于实际执行操作的“handle()”和帮助解析器找到正确函数的描述性属性。 为了对命令实现一些标准,我们有一个所有命令都需要从中派生的基类。

我的问题是这些实际上并没有用作类,从来没有任何命令的实例。

class command(ABC):
    '''
    class all commands inherit from
    '''

    @property
    @staticmethod
    @abstractmethod
    def name():
        '''
        returns the name of the command (which the parser acts on)
        '''
        pass

    @property
    @staticmethod
    @abstractmethod
    def help():
        '''
        returns the help text
        '''
        pass

    @property
    @staticmethod
    @abstractmethod
    def handle():
        '''
        contains the actual command handler, may return data
        '''
        pass

class commandPrint(command):
    '''
    example
    '''

    @staticmethod
    def name():
        return 'print'

    @staticmethod
    def help():
        return 'Print some string'

    @staticmethod
    def handle(inputString):
        print(inputString)
        return inputString

这很好用,但似乎有点“非 Pythonic”,因为我们从未创建这些命令的实例。此外,虽然这确实给出了一个框架,但 abc 的目的是没有用的——我们从不创建实例,所以我们永远不会看到缺少的抽象方法。

是否有更 pythonic 的方式来归档这种类型的接口(interface)?

最佳答案

如果你想明确地阻止这个类被实例化(抽象),你可以使用这个:

class Command():
    def __init__(self):
        raise NotImplementedError()

您还可以在基类的所有方法中引发此错误 NotImplementedError 而不是 pass 更像是一个接口(interface)(需要重新定义所有方法).

关于python - 没有实例的类 - 更多 pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024655/

相关文章:

python - 如何在 pymongo 中查找特定键的所有值?

python - 为什么用括号和逗号索引 numpy 数组的行为不同?

python - 更改列表中字典中的键值

python - 在类中包装全局变量(python)

python - 为什么我不能使用 PyPNG 往返图像?

python - 文件 "pylab.py"的用途是什么

python - 从字符串 pandas python 创建一个数据框

python-3.x - XGBClassifier() Python 3.x 中的子样本、colsample_bytree、colsample_bylevel

c++ - 将 C++ 类私有(private)变量转换为公共(public)变量

oop - 如何使用 Playground/Workspace(而不是通过系统浏览器)创建方法?