我有一个程序,其中变量来自显式值或延迟的求值。我希望他们在被叫时以同样的方式“回应”。
最小工作示例:
import random
class DelayedEvaluation:
def __init__(self, function):
assert callable(function), "Input argument {} is not callable and can thus not be a delayed evaluation.".format(function)
self.__delayed_evaluation = function
self.__class__ = type(self.__delayed_evaluation()) # Does not work!
def __repr__(self):
return self.__delayed_evaluation()
def __str__(self):
return "{}".format(self.__delayed_evaluation())
delayed_evaluation = DelayedEvaluation(lambda: 42)
print(delayed_evaluation) # Works.
print(delayed_evaluation + 1) # Does not work!
delayed_evaluation + 1 # Does not work!
for i in range(100):
value = random.choice((DelayedEvaluation(lambda: 42), 43))
print(value + 1) # Does not work when 'value' comes from 'DelayedEvaluation'.
在上面,我尝试通过引入类DelayedEvaluation
并将其类型设置为求值时函数值的类型来实现这一点。
我希望DelayedEvaluation(lambda: 42)
以与43
相同的方式“回复”。
我该如何解决?
不起作用的原因很简单。
延迟评估是由以下事实触发的,即打印需要对象的字符串表示形式,因此调用了DelayedEvaluation实例的函数__repr__
或__str__
。
如果您呼叫delayed_evaluation + 1
,则不会触发对__repr__
或__str__
的呼叫。
您可以做的是实现'+'运算符
def __add__(self,other):
return self.__delayed_evaluation() + other
如果它对其他运算符也有效,那么您必须实现所有您要处理的运算符。