gpt4 book ai didi

python 惰性变量?或者,延迟昂贵的计算

转载 作者:太空狗 更新时间:2023-10-29 17:41:37 25 4
gpt4 key购买 nike

我有一组非常大且计算成本高的数组,在任何给定运行中我的代码不一定需要所有数组。我想让他们的声明成为可选的,但理想情况下不必重写我的整个代码。

现在的例子:

x = function_that_generates_huge_array_slowly(0)
y = function_that_generates_huge_array_slowly(1)

我想做的事的例子:

x = lambda: function_that_generates_huge_array_slowly(0)
y = lambda: function_that_generates_huge_array_slowly(1)
z = x * 5 # this doesn't work because lambda is a function
# is there something that would make this line behave like
# z = x() * 5?
g = x * 6

虽然像上面那样使用 lambda 可以达到预期的效果之一 - 数组的计算会延迟到需要时 - 如果你多次使用变量“x”,则每次都必须计算它。我只想计算一次。

编辑:经过一些额外的搜索,看起来可以(大约)用类中的“惰性”属性(例如 http://code.activestate.com/recipes/131495-lazy-attributes/ )做我想做的事。我不认为有任何方法可以在不创建单独的类的情况下做类似的事情吗?

EDIT2:我正在尝试实现一些解决方案,但我遇到了一个问题,因为我不明白它们之间的区别:

class sample(object):
def __init__(self):
class one(object):
def __get__(self, obj, type=None):
print "computing ..."
obj.one = 1
return 1
self.one = one()

class sample(object):
class one(object):
def __get__(self, obj, type=None):
print "computing ... "
obj.one = 1
return 1
one = one()

我认为这些变量的一些变化是我正在寻找的,因为昂贵的变量旨在成为类的一部分。

最佳答案

问题的前半部分(重用值)很容易解决:

class LazyWrapper(object):
def __init__(self, func):
self.func = func
self.value = None
def __call__(self):
if self.value is None:
self.value = self.func()
return self.value

lazy_wrapper = LazyWrapper(lambda: function_that_generates_huge_array_slowly(0))

但是您仍然必须将它用作 lazy_wrapper() 而不是 lazy_wrapper

如果您要多次访问某些变量,使用它可能会更快:

class LazyWrapper(object):
def __init__(self, func):
self.func = func
def __call__(self):
try:
return self.value
except AttributeError:
self.value = self.func()
return self.value

这会使第一次调用变慢而后续调用变快。

编辑:我看到您找到了一个类似的解决方案,该解决方案要求您在类上使用属性。无论哪种方式都需要您重写每个惰性变量访问,因此只需选择您喜欢的即可。

编辑 2:您还可以:

class YourClass(object)
def __init__(self, func):
self.func = func
@property
def x(self):
try:
return self.value
except AttributeError:
self.value = self.func()
return self.value

如果你想访问 x 作为一个实例属性。不需要额外的类(class)。如果您不想更改类签名(通过使其需要 func),您可以将函数调用硬编码到属性中。

关于python 惰性变量?或者,延迟昂贵的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com