是否可以将方法作为参数传递给方法?
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
是否可以将方法作为参数传递给方法?
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
当前回答
示例:一个简单的函数调用包装器:
def measure_cpu_time(f, *args):
t_start = time.process_time()
ret = f(*args)
t_end = time.process_time()
return t_end - t_start, ret
其他回答
是的,函数(和方法)是Python中的第一类对象。以下工作:
def foo(f):
print "Running parameter f()."
f()
def bar():
print "In bar()."
foo(bar)
输出:
Running parameter f().
In bar().
使用Python解释器或IPython shell来回答这类问题非常简单。
下面是重新编写的示例,以显示一个独立的工作示例:
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()
是的,这是可能的。就叫它:
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
方法和其他对象一样都是对象。所以你可以传递它们,把它们存储在列表和字典中,做任何你喜欢的事情。它们的特殊之处在于它们是可调用对象,所以你可以对它们调用__call__。当你调用方法时,不管是否带参数,__call__都会被自动调用,所以你只需要编写methodToRun()。
这并不是您想要的,但是一个相关的有用工具是getattr(),它使用方法的名称作为参数。
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()