【发布时间】:2018-10-06 01:42:28
【问题描述】:
我有一个应用程序,其中(更大的一组)开发人员添加命令。这些命令由一组函数组成,主要是“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
这很好用,但似乎有点“unpythonic”,因为我们从不创建这些命令的实例。此外,虽然这确实给出了一个框架,但 abc 的目的是没有用的 - 我们从不创建实例,因此我们永远不会看到缺少的抽象方法。
有没有更 Pythonic 的方式来归档这种类型的接口?
【问题讨论】:
-
我不完全确定,但我认为 OO 方法对仅静态类没有任何问题。
-
你不能只使用存储函数的字典和至少需要名称、帮助和处理参数的字典创建函数吗?
-
我没有正确理解你的问题,但感觉就像你希望有一些东西
perform_operation_as_per_flag(flag)在这个函数里面你有标记的映射来调用相应的函数。尝试使用argparse函数add_mutually_exclusive_group() -
我认为您似乎正在寻找的是一个模块,只需从外部代码导入模块即可。摆脱这个“抽象”类,它们在这里并没有使任何事情变得更清楚。
-
@Abhishakegupta 我认为 argparse 对于我们的解决方案来说太过分了。不过谢谢你的建议
标签: python python-3.x oop