Python 将类方法作为参数传递给另一个类方法时出错
我试图将一个类方法作为参数传递给另一个类方法。下面是一个例子Python 将类方法作为参数传递给另一个类方法时出错,python,Python,我试图将一个类方法作为参数传递给另一个类方法。下面是一个例子 import time class MyClass(object): def doSomething(self,argument2,argument3): print argument2,argument3 def attemptTenTimes(self,fun,*args): attempt = 0 while True: try:
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).............
参数数:3
((,'argument2','argument3'),)
异常:doSomething()正好接受3个参数(给定2个)
参数数目:3
((,'argument2','argument3'),)
异常:doSomething()正好接受3个参数(给定2个)
参数数目:3
((,'argument2','argument3'),)
例外情况:doSomething()正好接受3个参数(给定2个)。。。。。。。。。。。。。
我将三个参数传递给doSomething函数,但是,这个异常不断出现。我以前使用过函数作为其他函数的参数,但这是我第一次在类的上下文中这样做。任何帮助都将不胜感激。谢谢。您还没有通过三个参数;你通过了两次。你需要这个:
MC.attemptTenTimes(MC.doSomething,*('argument2','argument3'))
或此(等效):
attempttimes
函数具有参数*args
,该参数将位置参数收集到一个元组中,该元组在本地称为args
。将整个元组作为唯一的位置参数传递给它,因此在本地有一个名为args
的变量,看起来像((MC,'argument2','argument3'),)
。因此,当您解包并将其传递给函数时,您只是传递内部元组
顺便说一句,当您将参数传递给len
时,也不应该将其解包,因为这样会抛出错误。您只需要len(args)
在上面的第12行
或者,您可以将AttemptTimes函数签名更改为:
def attemptTenTimes(self,fun,args):
然后可以像最初那样将整个args元组传递给它。不过,我相信使用
*args
更标准,而且我个人认为它更清晰。Grrr,我应该抓住它!你的回答很有帮助。我用了你说的,除了在元组中不需要“MC”。我用了*('argument2','argument3',)它成功了!不需要MC
的原因是MC.doSomething
已经绑定到您创建的实例,因此它只需要self
之外的两个参数。或者,您可以调用它MC.attemptTenTimes(MyClass.doSomething,MC,'arg2','arg3')
。当然,在绑定时使用它更容易,但我认为值得一提:-)值得一提的是:所讨论的两个方法都不是类方法classmethod
在Python中表示特定的内容,请参阅。
def attemptTenTimes(self,fun,args):