简体   繁体   English

将方法(带参数)传递给 python 中的另一个方法的最佳方法是什么

[英]What is the best way to pass a method (with parameters) to another method in python

What's the best way to pass a method and a method parameter to another method?将方法和方法参数传递给另一个方法的最佳方法是什么?

Is there a better way to do the following?有没有更好的方法来执行以下操作?

def method1(name)
    return 'Hello ' + name

def method2(methodToCall, methodToCallParams, question):
    greetings = methodToCall(methodToCallParams)
    return greetings + ', ' + question

method2(method1, 'Sam', 'How are you?')

If you want to package the invocation up in one hit, you can use the functools module:如果你想一键调用 package,你可以使用 functools 模块:

from functools import partial

def some_function(param_one, param_two):
    print "Param One: %s" % param_one
    print "Param Two: %s" % param_two

def calling_function(target):
    target()

calling_function(partial(some_function, "foo", "bar"))

You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature.你也可以用 functools.partial 做一些更精细的事情,比如只绑定一些参数,给你一个带有新签名的 function。 It's overkill in a lot of cases to use it but it certainly has it's place.在很多情况下使用它是矫枉过正的,但它肯定有它的位置。

You could do it this way:你可以这样做:

def method1(name):
    def wrapper():
        return 'Hello ' + name
    return wrapper

def method2(method, question):
    output = method()
    return output + ', ' + question

method2(method1(name = 'Sam'), 'How are you?')

You can of course pass some variables in the method() call too:当然,您也可以在 method() 调用中传递一些变量:

def method1(name):
    def wrapper(greeting):
        return greeting + name
    return wrapper

def method2(method, question):
    output = method(greeting = 'Hello ')
    return output + ', ' + question

method2(method1(name = 'Sam'), 'How are you?')

You can used functools.partial to do this, as jkp pointed out正如jkp 指出的那样,您可以使用functools.partial来执行此操作

However, functools is new in Python 2.5, so to handle this in the past I used the following code (this code is in the Python docs for functools.partial, in fact).但是,functools 是 Python 2.5 中的新功能,因此过去我使用以下代码来处理这个问题(实际上,此代码在 functools.partial 的 Python 文档中)。

# functools is Python 2.5 only, so we create a different partialfn if we are
# running a version without functools available
try:
    import functools
    partialfn = functools.partial
except ImportError:
    def partialfn(func, *args, **keywords):
        def newfunc(*fargs, **fkeywords):
            newkeywords = keywords.copy()
            newkeywords.update(fkeywords)
            return func(*(args + fargs), **newkeywords)
        newfunc.func = func
        newfunc.args = args
        newfunc.keywords = keywords
        return newfunc

Another option, if you are working on a Python version pre 2.5 is to use a lambda as a closure:另一种选择,如果您正在使用 Python 版本 pre 2.5 是使用 lambda 作为闭包:

def some_func(bar):
    print bar

def call_other(other):
    other()

call_other(lambda param="foo": some_func(param))

HTH高温高压

You're thinking of currying, where you bind a function and arguments together to be called later.您正在考虑使用 currying,将 function 和 arguments 绑定在一起以便稍后调用。 Usually currying is used so that you can add additional arguments at the time the function is actually called.通常使用柯里化,以便您可以在实际调用 function 时添加额外的 arguments。

Rather than re-write the wheel, here's a link to an example: http://code.activestate.com/recipes/52549/ .而不是重新编写轮子,这里是一个示例的链接: http://code.activestate.com/recipes/52549/

If, however, the case you've mocked up in the question really is that simple, you can pass a list of args as positional parameters, or a list of kwargs as named parameters, to another function.但是,如果您在问题中模拟的情况确实如此简单,您可以将 args 列表作为位置参数,或将 kwargs 列表作为命名参数传递给另一个 function。

def method1(name):
    return 'Hello %s' % name

args = ['Joe']
method1(*args)

def method1a(name=None, salutation=None):
    return 'Hello %s %s' % (name, salutation)

kwargs = {'name':'Joe', 'salutation':'Mr'}
method1a(**kwargs)

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

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