使用*args注入静态方法,接收类型作为第一个参数

2024-10-06 11:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输出是(前两行正确,其他两行不正确):

^{pr2}$

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

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


Tags: theto参数asargsbemethodclass
1条回答
网友
1楼 · 发布于 2024-10-06 11:19:26

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

相关问题 更多 >