将函数作为参数传递:Python

2024-10-01 00:19:12 发布

您现在位置: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),输出为Bye WorldBye WorldBye World

对于analyze(hello, 3),输出为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'异常


Tags: 对象函数selfobjhelloworldreturndef
2条回答

你能试试这个吗

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))
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()
obj.analyze(obj.hello, 3)

相关问题 更多 >