【发布时间】:2011-07-08 20:05:00
【问题描述】:
是否可以将函数放入数据结构中,而无需先用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) )
【问题讨论】:
-
不,不是。
# The word "myprint" is never used again. Why litter the namespace with it?你为什么要花这么多时间来摆脱一条对你没有任何伤害的线路? -
@phant0m, @Udi:我希望我的代码漂亮且易于阅读。在现实生活中,我有一个正则表达式-函数对对的列表,并在与正则表达式匹配的字符串上运行函数/处理程序。处理程序足够小,可以使列表之外的定义变得丑陋和不恰当。
-
我现在已经添加了真正的问题。我通常不喜欢这样做,因为它使问题更加具体。我可能会从发布它中学到更多,但不是通过标题找到问题的未来访问者。 (ping @phant0m)
-
那些函数名是很好的文档。如果你要让它们匿名,你的代码的阅读者将不得不花费更多的大脑周期来理解这些函数的作用。
-
如果你真的想要这些东西,你可能想切换到 perl。我知道 perl,但为了清楚起见,我使用 python。你可以正确地建模这个 Pattern,或者破解它。在后一种情况下,我认为命名空间污染不是您的主要问题。
标签: python anonymous-function lambda