在python中传递算术表达式而不评估它们

时间:2013-01-08 16:01:41

标签: python variables

我已经搜索过,无法找到我的问题的直接答案,所以如果之前已经发布/回答过,请道歉。我在python中工作,我需要传递包含变量的表达式,但我不希望它们立即被评估。

例如:

r = x*y

我希望程序记住,为了计算r,它需要乘以x和y而不是当时显式计算它。我尝试过使用:

x = None
y = None
r = x*y

但这不允许对变量进行操作。我使用字符串然后使用“eval”管理它,但它不是一个非常优雅的解决方案,而且它也很痛苦。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:4)

您可以使用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才能获得结果 - 但这不是很糟糕吗?

答案 1 :(得分:0)

您可以查看source code 实用程序的Math Evaluator,了解如何在以后创建表达式以供评估。 demonstration上的Ideone.com有助于显示代码可以完成的任务。

if __name__ == '__main__':
    # Run a simple demo that shows evaluator's capability.
    namespace = {}
    expression = tokens('x * y -> r')
    print expression
    evaluate('2 -> x; 3 -> y', namespace)
    expression.evaluate(namespace)
    print 'r =', namespace['r']
    alternate = Operation(Operation(Variable('x'), '+', Variable('y')), '->', Variable('r'))
    print alternate
    alternate.evaluate(namespace)
    print 'r =', namespace['r']