将类方法作为参数传递给另一个类方法时出错

2024-04-26 19:00:14 发布

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

我试图将一个类方法作为参数传递给另一个类方法。下面是一个例子。。。你知道吗

import time

class MyClass(object):

    def doSomething(self,argument2,argument3):
        print argument2,argument3

    def attemptTenTimes(self,fun,*args):
        attempt = 0
        while True:
            try:
                print 'Number of arguments: %s' % len(*args)
                print args
                output = fun(*args)
                return output
            except Exception as e:
                print 'Exception: %s' % e
                attempt += 1
                time.sleep(10)
                if attempt >= 10: return
                else: continue

MC = MyClass()
MC.attemptTenTimes(MC.doSomething,(MC,'argument2','argument3',))

输出是。。。。你知道吗

Number of arguments: 3
((<__main__.MyClass object at 0x7f7e6be4e390>, 'argument2', 'argument3'),)
Exception: doSomething() takes exactly 3 arguments (2 given)
Number of arguments: 3
((<__main__.MyClass object at 0x7f7e6be4e390>, 'argument2', 'argument3'),)
Exception: doSomething() takes exactly 3 arguments (2 given)
Number of arguments: 3
((<__main__.MyClass object at 0x7f7e6be4e390>, 'argument2', 'argument3'),)
Exception: doSomething() takes exactly 3 arguments (2 given).............

我将三个参数传递给doSomething函数,但是,这个异常不断出现。我以前使用过函数作为其他函数的参数,但这是我第一次在类的上下文中这样做。任何帮助都将不胜感激。谢谢。你知道吗


Tags: ofnumberobjectmainexceptionmyclassargsmc
1条回答
网友
1楼 · 发布于 2024-04-26 19:00:14

你没有通过三个论点;你通过了两个。你需要这个:

MC.attemptTenTimes(MC.doSomething,*('argument2','argument3'))

或此(等效):

MC.attemptTenTimes(MC.doSomething,'argument2','argument3')

attemptTenTimes函数具有参数*args,该参数将位置参数收集到本地称为args的元组中。将整个元组作为唯一的位置参数传递给它,因此在本地有一个名为args的变量,看起来像((MC,'argument2','argument3'),)。因此,当您解压它并将其传递给函数时,您只是传递内部元组。你知道吗

另外,在将参数传递给len时,也不应该对其进行解包,因为那样会引发错误。你只需要len(args)在12号线上。你知道吗

或者,您可以将Attemptentimes函数签名更改为:

def attemptTenTimes(self,fun,args):

然后可以像最初那样将整个args元组传递给它。不过,我相信使用*args更标准,而且我个人认为它更清晰。你知道吗

相关问题 更多 >