Skip to main content
 首页 » 编程设计

python之在 Python 中延迟评估/惰性评估

2024年11月01日10rubylouvre

我想延迟对类实例的成员函数的调用的评估,直到该实例实际存在为止。

最小工作示例:

class TestClass: 
 
    def __init__(self, variable_0): 
        self.__variable_0 = variable_0 
 
    def get_variable_0(self): 
        return self.__variable_0 
 
 
delayed_evaluation_0 = test_class.get_variable_0()  # What should I change here to delay the evaluation? 
test_class = TestClass(3) 
print(delayed_evaluation_0.__next__)  # Here, 'delayed_evaluation_0' should be evaluated for the first time. 

我尝试使用 lambda、yield 和生成器括号 () 但我似乎无法让这个简单的示例工作。

我该如何解决这个问题?

请您参考如下方法:

一个简单的 lambda 就可以了。调用时,该函数将从当前作用域中获取 test_class 变量,如果找到它,它将起作用,如下所示:

delayed_evaluation_0 = lambda : test_class.get_variable_0() 
test_class = TestClass(3) 
print(delayed_evaluation_0()) 

打印3