在Python中延迟评估/延迟评估 [英] Delay an evaluation / lazy evaluation in Python

查看:118
本文介绍了在Python中延迟评估/延迟评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

最小工作示例:

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.

我尝试使用lambdayield和生成器括号(),但是我似乎无法使这个简单的示例正常工作.

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?

推荐答案

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

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())

打印3

这篇关于在Python中延迟评估/延迟评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆