我有一个回调函数列表,我需要在触发事件时调用.这是惯用的蟒蛇吗?
def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
Run Code Online (Sandbox Code Playgroud)
Ste*_*202 17
使用map仅适用于无副作用(如函数print).也就是说,仅将它用于只返回某些东西的函数.在这种情况下,常规循环更惯用:
for f in lst:
f("event_info")
Run Code Online (Sandbox Code Playgroud)
编辑:同样,从Python 3.0开始,map返回迭代器而不是列表.因此在Python 3.0中,问题中给出的代码不会调用任何函数,除非显式计算生成器中的所有元素(例如,通过将调用封装到map内部list).幸运的是,2to3工具会警告:
档案map.py:
map(lambda x: x, range(10))
Run Code Online (Sandbox Code Playgroud)
2to3-3.0 map.py 输出:
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
--- map.py (original)
+++ map.py (refactored)
@@ -1,1 +1,1 @@
-map(lambda x: x, range(10))
+list(map(lambda x: x, list(range(10))))
RefactoringTool: Files that need to be modified:
RefactoringTool: map.py
RefactoringTool: Warnings/messages while refactoring:
RefactoringTool: ### In file map.py ###
RefactoringTool: Line 1: You should use a for loop here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |