简体   繁体   English

Python的表达评估机制

[英]Expression evaluation mechanism of Python

I used to believe for the Python expression f(g)(x) , the evaluation process is: 我曾经相信对于Python表达式f(g)(x) ,评估过程是:

  1. Evaluate f(g) , return function h ; 评估f(g) ,返回函数h
  2. Evaluate h(x) , return the final result. 评估h(x) ,返回最终结果。

But the code below shows this is not true: 但是下面的代码表明这是不正确的:

def double(x):
    return 2 * x

def double_or_zero(f):
    def f_or_zero(x):
        if x > 0:
            return f(x)
        else:
            return -999
    return f_or_zero

print(double_or_zero(double)(3))
print(double_or_zero(double)(-3))

When the first part (if it exists) double_or_zero(double) is evaluated, it can "see" the parameter ( 3 and -3 ) in the next step, which shows the from-left-to-right evaluation model is not true. 当评估了第一部分(如果存在) double_or_zero(double) ,它可以在下一步中 “看到”参数( 3-3 ),这表明从左到右的评估模型不正确。

So what is the expression evaluation mechanism for Python (2.x and 3.x)? 那么,Python(2.x和3.x)的表达式评估机制是什么?

Update 更新

Thanks to Bi Rico's answer, Python evaluates expression from left to right strictly. 感谢Bi Rico的回答,Python严格从左到右评估表达式。 Hope the code below can make it more clear: 希望下面的代码可以使它更清晰:

def double(x):
    return 2 * x

def f_or_zero(this_f):
    def this_f_or_zero(x):
        print('I am running with x = %s' % x)
        if x > 0:
            return this_f(x)
        else:
            return -999
    print('I am created: %s' % this_f_or_zero)
    return this_f_or_zero

double_or_zero = f_or_zero(double)
print(double_or_zero(3))
print(double_or_zero(-3))

Run it: 运行:

$ python demo.py
I am created: <function this_f_or_zero at 0x7f9f53786500>
I am running with x = 3
6
I am running with x = -3
-999

Why do you think that python can see the parameter when the first part is evaluated, it can't. 为什么您认为在评估第一部分时python可以看到该参数,但为什么看不到。 This example might make what's happening more clear. 这个例子可能使事情变得更清楚。 Your example works the same way. 您的示例以相同的方式工作。

def double(x):
    return 2 * x

def f_or_zero(this_f):
    def this_f_or_zero(x):
        if x > 0:
            return this_f(x)
        else:
            return 0
    return this_f_or_zero


double_or_zero = f_or_zero(double)
print(double_or_zero(3))
print(double_or_zero(-3))

double_or_zero is a function that behaves (mostly) like any other python function. double_or_zero是一个函数,其行为(大部分)与任何其他python函数类似。 It just so happens that this function is created dynamically and returned by a call to another function. 碰巧的是,该函数是动态创建的,并通过调用另一个函数返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM