2012-10-10 74 views
0

根据我在this文章中看到的内容,我试图编写这段代码,但它给了我错误。调用成员函数并在python中传递带有map函数的参数

ticklabels = ax.get_xticklabels() 
set_color = operator.methodcaller('set_color("b")') 
ticklabels[0].set_color('b') # this runs fine 
map(set_color, ticklabels) #error is here 

错误代码:

map(set_color, ticklabels) AttributeError: 'Text' object has no attribute 'set_color("b")'

你不能传递参数在methodcaller功能?

+0

是否'图(拉姆达X:x.set_color,ticklabels)'工作? – halex

+0

@halex,是的,你的代码也可以工作,并在提到的文章中提到。我只是不想使用'lambda'。谢谢你提到这一点。 – rowman

+0

'lambda'变体应该是'map(lambda x:x.set_color('b'),ticklabels)' –

回答

2

我想你需要:

set_color = operator.methodcaller('set_color', 'b') 

第一个参数是要调用的方法,后续参数将被传递给该方法被调用时。

然后,您可以测试它的工作原理是这样做的:

set_color(ticklabels[0]) 
+0

是的,没有阅读'methodcaller'的文档。它在那里被提及。 – rowman

相关问题