是否可以在不使用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) )
# 单词“myprint”再也没有被使用过。为什么要在命名空间中乱扔呢?
你为什么要花费这么多时间来消除一行对你没有任何影响的代码呢? - phant0m