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

时间:2013-03-27 15:22:53

标签: 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传递了三个参数,但是,这个异常不断出现。之前我曾使用函数作为其他函数的参数,但这是我第一次在类的上下文中执行它。任何帮助,将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

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

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

或此(等效):

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

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

顺便说一句,当你将args传递给len时,你也不应该解压缩args,因为这会引发错误。你只想在第12行看到len(args)

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

def attemptTenTimes(self,fun,args):

然后你可以将整个args元组传递给它,就像你原来那样。我相信使用*args更为标准,而且我个人觉得它更清楚。

相关问题