将函数作为参数传递: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

这是有道理的,但在类Objects中执行相同操作时,会抛出一个错误。例如:

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

最新更新