如何在Python中将方法作为参数传递

Dan*_*Dan 165 python parameter-passing

是否可以将方法作为参数传递给方法?

self.method2(self.method1)

def method1(self):
    return 'hello world'

def method2(self, methodToRun):
    result = methodToRun.call()
    return result
Run Code Online (Sandbox Code Playgroud)

Dav*_*d Z 235

是的,只需使用方法的名称,就像你写的那样.方法/函数是Python中的对象,就像其他任何东西一样,你可以将它们传递给你做变量的方式.实际上,您可以将方法(或函数)视为一个变量,其值是实际的可调用代码对象.

仅供参考,没有call方法 - 我认为它已被调用__call__,但您不必明确调用它:

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)
Run Code Online (Sandbox Code Playgroud)

  • @David Z如何在方法1中传递参数? (2认同)
  • 我对你明显地将“方法”和“函数”这个词混为一谈感到困惑。`def method1(spam):` 是函数定义,而不是方法定义。 (2认同)
  • 您回答的问题与所提出的问题不同。OP询问您是否可以传递一个方法作为参数,例如“func(obj.method)”。您解释了如何将函数作为参数传递,例如“func(other_func)”,但同时将函数称为方法。我发现这很令人困惑。 (2认同)

小智 34

对的,这是可能的.只需称呼它:

class Foo(object):
    def method1(self):
        pass
    def method2(self, method):
        return method()

foo = Foo()
foo.method2(foo.method1)
Run Code Online (Sandbox Code Playgroud)

  • 如果没有实例“foo”怎么办? (4认同)
  • 那么你根本不需要 foo,例如:`def method1(): pass def method2(method) return method() method2(method1)` (2认同)

Tre*_*ent 12

以下是您重写的示例,以显示一个独立的工作示例:

class Test:
    def method1(self):
        return 'hello world'

    def method2(self, methodToRun):
        result = methodToRun()
        return result

    def method3(self):
        return self.method2(self.method1)

test = Test()

print test.method3()
Run Code Online (Sandbox Code Playgroud)


Fro*_*ide 8

如果您想将类的方法作为参数传递但还没有要调用它的对象,则可以在将其作为第一个参数(即“self”)后简单地传递该对象争论)。

class FooBar:

    def __init__(self, prefix):
        self.prefix = prefix

    def foo(self, name):
        print "%s %s" % (self.prefix, name)


def bar(some_method):
    foobar = FooBar("Hello")
    some_method(foobar, "World")

bar(FooBar.foo)
Run Code Online (Sandbox Code Playgroud)

这将打印“Hello World”


Scr*_*tch 8

使用一个lambda函数。
所以如果你没有争论,事情就会变得非常简单:

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)
Run Code Online (Sandbox Code Playgroud)

但是假设您有一个(或多个)参数method1

def method1(param):
    return 'hello ' + str(param)

def method2(methodToRun):
    result = methodToRun()
    return result
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地调用method2as method2(lambda: method1('world'))

method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader
Run Code Online (Sandbox Code Playgroud)

我发现这比这里提到的其他答案要干净得多。


lt_*_*ije 5

是; 函数(和方法)是Python中的第一类对象.以下作品:

def foo(f):
    print "Running parameter f()."
    f()

def bar():
    print "In bar()."

foo(bar)
Run Code Online (Sandbox Code Playgroud)

输出:

Running parameter f().
In bar().
Run Code Online (Sandbox Code Playgroud)

使用Python解释器或者对于更多功能,使用IPython shell 来回答这些问题是微不足道的.