开发者社区> 问答> 正文

Python operator.methodcaller()无法正确处理参数?

我想在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

展开
收起
is大龙 2020-03-24 19:02:19 1356 0
1 条回答
写回答
取消 提交回答
  • 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

    2020-03-24 19:02:28
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载