最pythonic的方式可能是列表理解:
results = [b.get_a().do_something() for b in collection]
如果要缓存调用B.get_a()
,可以使用memoization。自己进行记忆的一种简单方法如下所示:
cache = None
# ...
class B:
def get_a(self):
global cache
if cache is None:
cache = A()
return cache
如果要在多个地方使用缓存,则需要根据键缓存结果以区分它们,并且为了方便起见,编写一个装饰器,您可以简单地包装要缓存其结果的函数。
在Python Algorithms: Mastering Basic Algorithms in the Python Language中找到了一个很好的例子(参见这个问题)。针对您的情况进行了修改,不使用函数参数,而是使用函数名作为缓存键,它看起来像这样:
from functools import wraps
def memoize(func):
cache = {}
key = func.__name__
@ wraps(func)
def wrap(*args):
if key not in cache:
cache[key] = func(*args)
return cache[key]
return wrap
class A:
def do_something(self):
return 1
class B:
@memoize
def get_a(self):
print "B.get_a() was called"
return A()
collection = [B(), B()]
results = [b.get_a().do_something() for b in collection]
print results
输出:
B.get_a() was called
[1, 1]