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

self.method2(self.method1)

def method1(self):
    return 'hello world'

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

当前回答

这并不是您想要的,但是一个相关的有用工具是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')()

其他回答

使用lambda函数。 所以如果你没有争论,事情就变得很琐碎:

def method1():
    return 'hello world'

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

method2(method1)

但是假设你在method1中有一个(或多个)参数:

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

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

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

method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader

我发现这个答案比这里提到的其他答案清晰得多。

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

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()

这并不是您想要的,但是一个相关的有用工具是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')()

方法和其他对象一样都是对象。所以你可以传递它们,把它们存储在列表和字典中,做任何你喜欢的事情。它们的特殊之处在于它们是可调用对象,所以你可以对它们调用__call__。当你调用方法时,不管是否带参数,__call__都会被自动调用,所以你只需要编写methodToRun()。

示例:一个简单的函数调用包装器:

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