3

静的メソッドを注入する必要があるクラスがいくつかあります。この静的メソッドは、(インスタンスではなく) タイプを最初の引数として呼び出し、残りのすべての引数を実装に渡す必要があります ( ideone の例)。

# function which takes class type as the first argument
# it will be injected as static method to classes below
def _AnyClass_me(Class,*args,**kw):
    print Class,str(args),str(kw)

 # a number of classes
class Class1: pass
class Class2: pass

# iterate over class where should be the method injected
# c is bound via default arg (lambda in loop)
# all arguments to the static method should be passed to _AnyClass_me
# via *args and **kw (which is the problem, see below)
for c in (Class1,Class2):
    c.me=staticmethod(lambda Class=c,*args,**kw:_AnyClass_me(Class,*args,**kw))

# these are OK
Class1.me()    # work on class itself
Class2().me()  # works on instance as well

# fails to pass the first (Class) arg to _anyClass_me correctly
# the 123 is passed as the first arg instead, and Class not at all
Class1.me(123)
Class2().me(123)

出力は次のとおりです (最初の 2 行は正しく、他の 2 行は正しくありません)。

__main__.Class1 () {}
__main__.Class2 () {}
123 () {}
123 () {}

デフォルトの引数が混在しているラムダ行に問題があると思われますが、*argsそれを整理することはできません。

他の引数が存在する場合に Class オブジェクトを正しく渡すにはどうすればよいですか?

4

1 に答える 1

3

静的メソッドの代わりにクラス メソッドを使用する必要があります。

for c in (Class1,Class2):
    c.me = classmethod(_AnyClass_me)

>>> Class1.me()
__main__.Class1 () {}
>>> Class2().me()
__main__.Class2 () {}
>>> Class1.me(123)
__main__.Class1 (123,) {}
>>> Class2().me(123)
__main__.Class2 (123,) {}
于 2012-05-17T18:25:17.823 に答える