我有一个回调函数列表,当事件触发时我需要调用这些函数。
这是惯用的Python吗?
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?
Use map
仅适用于没有副作用的函数(例如print
)。也就是说,仅将其用于仅返回某些内容的函数。在这种情况下,常规循环更惯用:
for f in lst:
f("event_info")
Edit:另外,从 Python 3.0 开始,map http://docs.python.org/3.0/library/functions.html#map返回一个迭代器而不是列表。因此,在Python 3.0中,问题中给出的代码不会调用any函数,除非生成器中的所有元素都被显式求值(例如,通过封装对map
inside list http://docs.python.org/3.0/library/functions.html#list)。幸运的是2to3 http://docs.python.org/library/2to3.html工具会对此发出警告:
File map.py
:
map(lambda x: x, range(10))
2to3-3.0 map.py
output:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)