如果不先用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。
我认为创建匿名函数的难度有点小。你真正想做的是保持相关代码在一起,并使代码整洁。所以我想装饰师可能会为你工作。
更好的解决实际问题的干法:
继续使用模块化自包含解决方案的Gareth's干净方法:
相关问题 更多 >
编程相关推荐