我试图在Python中将“子命令”系统实现为可继承类。我预期的用例是这样的:
^{1}$我将Command.subcommand
实现为一个静态方法,一切都很好,直到我试图向父类添加一个子命令,我得到了TypeError: 'staticmethod' object is not callable
。事后看来,this显然行不通:
到目前为止,我发现的唯一替代方法是在父类之外声明subcommand
修饰符,然后在类定义完成后注入它。在
def subcommand(method):
method.is_subcommand = True
return method
class Command(object):
@subcommand
def common(self):
print "this subcommand is available to all child classes"
Command.subcommand = staticmethod(subcommand)
del subcommand
然而,作为一个在添加装饰器之前从未使用过Python的人,我觉得这很笨拙。有没有更优雅的方法来完成这一点?在
我可以想出两种解决这个问题的办法。最简单的方法是在父类中使用完它之后,使它成为一个静态方法:
这有点脆弱,因为在将它变成静态方法之后,不能在父类中使用它。更可靠的方法是添加一个中间类:
^{pr2}$现在可以从}继承所有类。在
CommandBase
而不是{相关问题 更多 >
编程相关推荐