파이썬에서 함수 목록을 클래스 속성으로 저장 한 일부 오래된 코드가 있습니다. 이러한 목록은 일종의 이벤트 후크로 사용됩니다.함수 목록을 호출하는 파이썬 one-liner
적절한 인수를 사용하여 목록의 각 함수를 호출하려면 map
과 lambda
식을 혼합하여 한 줄짜리 함수를 사용했습니다. 지금은이 같은 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
전화를 쓸 수있는 더 나은 방법이 있나요?
'operator.methodcaller'는 나에게 새로운 것입니다 :) 그러나 명확하게하기 위해 그것을 사용할 것이라고 확신하지 못합니다. 파이썬 3에서'map'에 대한 경고를 보내 주셔서 감사합니다. –