Skip to main content
 首页 » 编程设计

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

2025年05月04日9www_RR

我有一个应用程序,(更多的)开发人员在其中添加了命令。这些命令由一组函数组成,主要是用于实际执行操作的“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)(需要重新定义所有方法).