python 函数调用列表,函数调用列表的Python oneliner

我有一些旧代码,其中我将函数列表作为类属性存储在Python中。这些列表被用作一种事件钩子。在

为了使用适当的参数调用列表中的每个函数,我使用了一行程序,将map与{}表达式混合使用。我现在担心使用这样的lambda表达式会有不必要的开销。。我想推荐的方法是删除map和lambda,只使用标准for循环,以提高可读性。在

但是,有没有更好(读得更快)的一行代码来实现这一点呢?在

例如:class Foo:

"""Dummy class demonstrating event hook usage."""

pre = [] # list of functions to call before entering loop.

mid = [] # list of functions to call inside loop, with value

post = [] # list of functions to call after loop.

def __init__(self, verbose=False, send=True):

"""Attach functions when initialising class."""

self._results = []

if verbose:

self.mid.append( self._print )

self.mid.append( self._store )

if send:

self.post.append( self._send )

def __call__(self, values):

# call each function in self.pre (no functions there)

map( lambda fn: fn(), self.pre )

for val in values:

# call each function in self.mid, with one passed argument

map( lambda fn: fn(val), self.mid )

# call each fn in self.post, with no arguments

map( lambda fn: fn(), self.post )

def _print(self, value):

"""Print argument, when verbose=True."""

print value

def _store(self, value):

"""Store results"""

self._results.append(value)

def _send(self):

"""Send results somewhere"""

# create instance of Foo

foo = Foo(verbose=True)

# equivalent to: foo.__call__( ... )

foo( [1, 2, 3, 4] )

有没有更好的方法来编写那些单行map调用?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值