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)
小智 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)
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)
如果您想将类的方法作为参数传递但还没有要调用它的对象,则可以在将其作为第一个参数(即“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”
使用一个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)
我发现这比这里提到的其他答案要干净得多。
是; 函数(和方法)是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 来回答这些问题是微不足道的.