我将在Python中实现一个可继承的“子命令”系统。我期望的使用场景是类似于以下内容:
到目前为止,我找到的唯一替代方法是在父类外部声明
from command import Command
import sys
class MyCommand(Command):
@Command.subcommand
def foo(self):
print "this can be run as a subcommand"
def bar(self):
print "but this is a plain method and isn't exposed to the CLI"
MyCommand()(*sys.argv)
# at the command line, the user runs "mycommand.py foo"
我将Command.subcommand
实现为静态方法,一切都很好,直到我尝试向父类添加子命令时,出现了TypeError:'staticmethod' object is not callable
。回想起来,显然这样行不通:
class Command(object):
@staticmethod
def subcommand(method):
method.is_subcommand = True
return method
@subcommand
def common(self):
print "this subcommand is available to all child classes"
到目前为止,我找到的唯一替代方法是在父类外部声明
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 加入装饰器之前从未使用过 Python 的人来说,这种方式感觉非常笨拙。有没有更优雅的方法来实现这个呢?
import command ... class MyCommand(command.Command)
(感觉多余)或者from command import * ... @subcommand
(感觉像是在污染命名空间)。 - Ben BlankCommand
类层次结构为您做了什么?你知道,面向对象编程不仅仅是关于类。 - Karl Knechtel