如何将类方法作为参数传递给该类外部函数?

pep*_*dip 5 python methods arguments class

这对我来说是这样的:

class SomeName:
  def __init__(self):
    self.value = "something"
  def some_method(self):
    print self.value

def external_func(instance, method):
  method(instance)

external_func(SomeName(), SomeName.some_method)
Run Code Online (Sandbox Code Playgroud)

这似乎正常工作。这是正确的方法吗?

bru*_*ers 5

您的代码是“技术上正确的”(它可以满足您的要求)但是 - 至少在您的示例中 - 非常无用:

def external_func(instance, method):
  method(instance)

external_func(SomeName(), SomeName.some_method)
Run Code Online (Sandbox Code Playgroud)

是相同的:

def external_func(method):
  method()

external_func(SomeName().some_method)
Run Code Online (Sandbox Code Playgroud)

FWIW 与以下相同:

SomeName().some_method()
Run Code Online (Sandbox Code Playgroud)

但我假设你已经理解了这一点。

现在您可能有理由尝试将方法和实例都传递给external_func(),或者可能有更好的方法来解决您的实际问题......


小智 0

如果您的方法中没有使用实例数据,您可以传递SomeName().some_method或 makesome_metod staticmethod或。classmethod

查看文档以了解有关staticmethod和 的更多信息classmethod