电子说
Python函数比我们想象的更为灵活。由于Python函数是对象,所以函数对象可以赋值给其他的名字、传递给其他函数、嵌入到数据结构、从一个函数返回给另一个函数,等等,就好像它们是简单的数字或字符串。
下面的代码演示了把一个函数对象赋给其他的名称并调用它:
>>>def echo(message): # Name echo assigned to function object
... print(message)
...
>>>echo('Direct call') # Call object through original name
Direct call
>>>x = echo # Now x references the function too
>>>x('Indirect call!') # Call object through name by x()
Indirect call!
下面的代码演示了将函数通过参数来进行传递:
>>>def indirect(func,arg):
... func(arg) # Call the passed-in object by adding ()
...
>>>indirect(echo,'Argument call!') # Pass the function to another function
Argument call!
我们甚至可以把函数对象填入到数据结构中,就好像它们是整数或字符串一样:
>>>schedule = [ (echo,'Spam!'),(echo,'Ham!') ]
>>>for (func,arg) in schedule:
... func(arg) # Call functions embedded in containers
...
Spam!
Ham!
函数也可以创建并返回以便之后使用:
>>>def make(label): # Make a function but don't call it
... def echo(message):
... print(label + ':' + message)
... return echo
...
>>>F = make('Spam') # Label in enclosing scope is retained
>>>F('Ham!') # Call the function that make returned
Spam:Ham!
>>>F('Eggs!')
Spam:Eggs!
Python的通用对象模式和无须类型声明使得该编程语言有了令人惊讶的灵活性。
全部0条评论
快来发表一下你的评论吧 !