3

I have several class where I need to inject a static method; this static method should be called with type (not instance) as the first argument, and pass all remaining args to the implementation (the example at 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)

The output is (first two lines correct, other two incorrect):

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

I suspect there is a problem in the lambda line, in the mixture of default argument with *args but I am unable to sort it out.

How can I have the Class object being passed correctly in presence of other args?

eudoxos
  • 18,545
  • 10
  • 61
  • 110

1 Answers1

3

You need to use a class method instead of a static method.

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,) {}
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • COOL! My real classes have common base class and all I was trying to do was implementing `classmethod` which I did not know -- the same static method, which knows the class on which it was called. Thanks! Nice to see how many cool corners python has. – eudoxos May 17 '12 at 18:29