Delay an evaluation / lazy evaluation in Python

妖精的绣舞 提交于 2019-12-23 23:24:32

问题


I want to delay the evaluation of a call to a member function of an instance of a class until this instance actually exists.

Minimum working example:

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.

I tried using lambda, yield and generator parentheses () but I can't seem to get this simple example to work.

How do I solve this problem?


回答1:


a simple lambda works. When called, the function will fetch test_class variable from the current scope, and if it finds it, that will work, like below:

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

prints 3



来源:https://stackoverflow.com/questions/57687709/delay-an-evaluation-lazy-evaluation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!