【问题标题】:inject static method with *args, receiving type as the first argument使用 *args 注入静态方法,接收类型作为第一个参数
【发布时间】:2012-05-17 18:14:35
【问题描述】:

我有几个类需要注入静态方法;这个静态方法应该以类型(不是实例)作为第一个参数来调用,并将所有剩余的参数传递给实现(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)

输出是(前两行正确,另外两行不正确):

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

我怀疑 lambda 行存在问题,默认参数与 *args 混合使用,但我无法解决。

如何在存在其他参数的情况下正确传递 Class 对象?

【问题讨论】:

    标签: python static-methods inject


    【解决方案1】:

    您需要使用class 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,) {}
    

    【讨论】:

    • 酷!我真正的类有共同的基类,而我所做的只是实现我不知道的classmethod——同样的静态方法,它知道调用它的类。谢谢!很高兴看到 python 有多少很酷的角落。
    猜你喜欢
    • 2018-05-20
    • 2014-01-24
    • 2011-10-02
    • 2016-02-15
    • 1970-01-01
    • 2011-03-06
    • 2019-05-20
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多