因为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'
异常
你能试试这个吗
相关问题 更多 >
编程相关推荐