是否可以将函数放入数据结构中,而无需先用 def
为其命名?
# This is the behaviour I want. Prints "hi".
def myprint(msg):
print msg
f_list = [ myprint ]
f_list[0]('hi')
# The word "myprint" is never used again. Why litter the namespace with it?
lambda 函数的主体受到严格限制,所以我不能使用它们。
编辑:作为引用,这更像是我遇到问题的真实代码。
def handle_message( msg ):
print msg
def handle_warning( msg ):
global num_warnings, num_fatals
num_warnings += 1
if ( is_fatal( msg ) ):
num_fatals += 1
handlers = (
( re.compile( '^<\w+> (.*)' ), handle_message ),
( re.compile( '^\*{3} (.*)' ), handle_warning ),
)
# There are really 10 or so handlers, of similar length.
# The regexps are uncomfortably separated from the handler bodies,
# and the code is unnecessarily long.
for line in open( "log" ):
for ( regex, handler ) in handlers:
m = regex.search( line )
if ( m ): handler( m.group(1) )
最佳答案
这是基于 Udi's nice answer .
我认为创建匿名函数的难度有点像红鲱鱼。您真正想做的是将相关代码保持在一起,并使代码整洁。所以我认为装饰器可能适合你。
import re
# List of pairs (regexp, handler)
handlers = []
def handler_for(regexp):
"""Declare a function as handler for a regular expression."""
def gethandler(f):
handlers.append((re.compile(regexp), f))
return f
return gethandler
@handler_for(r'^<\w+> (.*)')
def handle_message(msg):
print msg
@handler_for(r'^\*{3} (.*)')
def handle_warning(msg):
global num_warnings, num_fatals
num_warnings += 1
if is_fatal(msg):
num_fatals += 1
关于python - 根据正则表达式选择要调用的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629876/