将函数作为参数传递:Python

乌特卡什

由于 Python 中的函数是对象,因此我们可以将它们传递给其他函数。例如:

def hello(x) :
    return "Hello World"*x
def bye(x) :
    return "Bye World"*x
def analyze(func,x) :
    return func(x)

对于analyze(bye, 3)OUTPUT 是Bye WorldBye WorldBye World

对于analyze(hello, 3)OUTPUT 是Bye World WorldHello World

这是有道理的,但在执行相同的类内对象时,它会引发错误。例如:

class Greetings:
   def __init__(self):
      pass
   def hello(self, x) :
      return "Hello World"*x
   def bye(self, x) :
      return "Bye World"*x
   def analyze(self, func, x) :
      return self.func(x)

驱动程序代码:

obj = Greetings()
obj.analyze(hello, 3)

投掷 TypeError: analyze() missing 1 required positional argument: 'x'

我什至试过 obj.analyze(obj, hello, 3)

然后它抛出AttributeError: type object 'Greetings' has no attribute 'func'异常。

马兰·索斯里

你可以试试这个吗

class Greetings:
   def __init__(self):
      pass

   def hello(self, x) :
      return "Hello World"*x

   def bye(self, x) :
      return "Bye World"*x

   def analyze(self, func, x) :
      return func(x)

obj = Greetings()
print(obj.analyze(obj.hello, 3))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章