関数のリストを Python にクラス属性として保存した古いコードがあります。これらのリストは、一種のイベント フックとして使用されます。
map
リスト内の各関数を適切な引数で呼び出すために、式を組み合わせてワンライナーを使用しましlambda
た。このような式を使用すると不要なオーバーヘッドが発生するのではないかと心配しています。読みやすさのために、両方を削除して標準の for ループを使用するlambda
ことをお勧めします。map
lambda
ただし、これを行うためのより良い(より速く読む)ワンライナーはありますか?
例えば:
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
これらのワンライナー呼び出しを記述するより良い方法はありますか?