我想在python函数内部使用operator.methodcaller()
函数。但是,传递参数列表时,我收到奇怪的错误消息。
python文档使我相信,这通常应该不是问题:
返回一个可调用对象,该对象在其操作数上调用方法名称。如果给出了其他参数和/或关键字参数,它们也将被赋予方法。例如:
在f = methodcaller('name')之后,调用f(b)返回b.name()。
在f = methodcaller('name','foo',bar = 1)之后,调用f(b)返回b.name('foo',bar = 1)。
我在哪里错了?有没有其他简单的选择?
我编写了一个简短的代码示例来说明我的问题:
import operator
class CallTest:
def __init__(self):
self.x = 1
self.y = 2
def mutate(self, new_x, some_y = 2):
self.x = new_x
self.y = some_y
def map_something(func, iterable):
""" This doesn't work and that's as expected. The error shows that the methodcaller is referencing
the correct object though.
"""
for i in iterable:
func(i)
def map_something_else(func, iterable, \*rgs, \*kwargs):
""" Why doesn't this work? And are there alternatives? """
for i in iterable:
func(i, \*rgs, \*kwargs)
def map_differently(func, iterable, \*rgs, \*kwargs):
""" This works as expected but is kind of pointless in this case because i could replace this
with getattr()
"""
for i in iterable:
operator.methodcaller(func, \*rgs, \* kwargs)(i)
if __name__ == '__main__':
caller = operator.methodcaller('mutate')
objs = [CallTest() for i in range(0, 2)]
# map_something(caller, objs) # As expected we get: TypeError: mutate() missing 1 required positional argument: 'new_x'
# map_something_else(caller, objs, 5) # TypeError: methodcaller expected 1 argument, got 2
# map_something_else(caller, objs, 5, some_y=3) # TypeError: methodcaller() takes no keyword arguments
map_differently('mutate', objs, 5, some_y=3) # This works as expected.
for obj in objs:
print(obj.x, obj.y)
问题来源:stackoverflow
operator.methodcaller
仅在创建时接受其他参数。您试图在调用methodcaller时提供额外的参数。
它是这样的:
mc = operator.methodcaller('method_name', additional_arg)
mc(obj)
不是这样的:
mc = operator.methodcaller('method_name')
mc(obj, additional_arg)
这就是您的map_something_else
想要做的。
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。