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
必要があります-しかしそんなに悪くないですよね?