你可以使用一个lambda
表达式:
>>> x = None
>>> y = None
>>> r = lambda : x*y
>>> r()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
>>> x = 1
>>> y = 2
>>> r()
2
你甚至可以更喜欢一门课:
class DeferredEval(object):
def __init__(self,func):
self.func = func
def __call__(self):
return self.func()
def __add__(self,other):
return self.func() + other
def __radd__(self,other):
return other + self.func()
x = None
y = None
r = DeferredEval(lambda:x*y)
try:
a = 1 + r
except TypeError as err:
print "Oops, can't calculate r yet -- Reason:",err
x = 1
y = 2
print 1 + r
print r + 1
输出:
Oops, can't calculate r yet -- Reason: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
3
3
当然,如果你想做一些不是加法、减法的事情,你需要在这里添加一大堆更多的方法……当然,你必须实际调用 r
才能得到你的结果——但是这还不错吧?