问题
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