Python编程中的回调与函数特性及应用技巧
1. 回调与一等函数概念
回调和传递函数的概念对于部分开发者来说可能比较陌生,但深入了解它是很有价值的,这样在使用时能更好地掌握,或者在看到其应用时能理解其原理。在Python里,函数属于“一等公民”,这意味着函数可以像对象一样被传递和处理,因为实际上它们就是对象。
以下是展示函数作为一等公民的示例代码:
In [1]: def foo(): ...: print foo ...: ...: In [2]: foo Out[2]: <function foo at 0x1233270> In [3]: type(foo) Out[3]: <type 'function'> In [4]: dir(foo) Out[4]: ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']