简体   繁体   English

是否有像`lambda x,y:x.custom_method(y)`这样的标准功能代码?

[英]Is there a standard function code like `lambda x, y: x.custom_method(y)`?

I know that I can call magic methods using functions from operator module, for example: 我知道我可以使用operator模块中的函数来调用魔术方法,例如:

operator.add(a, b)

is equal to 等于

a.__add__(b)

Is there a standard function for calling a custom method (like operator.methodcaller but also accepts method arguments when called)? 是否有用于调用自定义方法的标准函数(例如operator.methodcaller但在调用时也接受方法参数)? Currently I have code like this: 目前,我有这样的代码:

def methodapply(name):
    """Apply a custom method.

    Usage:
        methodapply('some')(a, *args, **kwargs) => a.some(*args, **kwargs)

    """
    def func(instance, *args, **kwargs):
        return getattr(instance, name)(*args, **kwargs)
    func.__doc__ = """Call {!r} instance method""".format(name)
    return func

Yes, it is still called operator.methodcaller() : 是的,它仍然被称为operator.methodcaller()

Return a callable object that calls the method name on its operand. 返回一个可调用对象,该对象在其操作数上调用方法名称 If additional arguments and/or keyword arguments are given, they will be given to the method as well. 如果给出了其他参数和/或关键字参数,它们也将被赋予方法。 For example: 例如:

  • After f = methodcaller('name') , the call f(b) returns b.name() . f = methodcaller('name') ,调用f(b)返回b.name()
  • After f = methodcaller('name', 'foo', bar=1) , the call f(b) returns b.name('foo', bar=1) . f = methodcaller('name', 'foo', bar=1) ,调用f(b)返回b.name('foo', bar=1)

This inverts the chain a little from what you want; 这会使您想要的链条有些许颠倒。 you need to tell methodcaller() up-front what arguments to pass in. 您需要methodcaller()告诉methodcaller()要传入的参数。

There is no standard-library callable that'll build a method caller that accepts both the instance and the arguments. 没有标准库可调用的对象,它不会构建一个同时接受实例和参数的方法调用程序。

However, if your sequence of objects you are going to apply this to is homogenous, you can instead just use the unbound method; 但是,如果要应用的对象序列是同质的,则可以改用unbound方法; unbound methods take self as the first argument. 未绑定方法将self作为第一个参数。 So this works: 所以这工作:

from itertools import 
map(str.split, list_of_strings, [','] * len(list_of_strings), range(len(list_of_strings)))

which will split strings on commas with a growing limit; 它将以逗号分隔字符串的限制越来越大; each time map() calls str.split() (an unbound method), it'll pass in a str object from the list_of_strings list, a ',' string, and an integer argument ranging from 0 to len(list_of_strings) - 1 . 每次map()调用str.split() (一种未绑定方法)时,它将传入list_of_strings列表中的str对象,一个','字符串以及一个从0len(list_of_strings) - 1的整数参数len(list_of_strings) - 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM