私はPythonの継承可能クラスとして "サブコマンド"システムを実装しようとしています。私は、静的メソッドとしてCommand.subcommand
を実装し、私は私のTypeError: 'staticmethod' object is not callable
を得た親クラスにサブコマンドを追加しようとしたまですべてがうまく働いていたクラス定義内でも使用できるクラス内のデコレータの定義
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"
:私の期待のユースケースは、のようなものです。後知恵では、thisが動作しないことは明らかです:
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を使用したことのない人物として、これは私にとって非常に気難しいものです。これを達成するよりエレガントな方法はありますか?
最初の質問は、そのクラスがデコレータの束に使用されていない限り、クラスのメソッドとしてデコレータを実装する理由です。それが何であれ、なぜあなたはデコレータを「共通」にしていますか?あなたのクラスデザインがちょっと変わっているので、それはおそらくclunkyだと感じています。:) –
このデコレータがあなたのために何を達成したいと考えていますか? Pythonは既に、サブコマンドが何であるかを知っています。なぜなら、他のサブクラスであるクラスを知っているからです。 –
@Lennart - 純粋に輸入美学のため。私は 'import command ... class MyCommand(command.Command)'(冗長な感じ)や 'from command import * ... @ subcommand'(名前空間を汚染するような感じ)のファンではありませんでした。 –