如何使用 Python 代码理解动态范围? [英] How to understand dynamic scoping using Python code?

查看:29
本文介绍了如何使用 Python 代码理解动态范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名来自 Python 背景的程序员,通常使用词法范围,我想了解动态范围.网上查了下,还是不太明白.例如,我已阅读此页面让我的事情变得容易多了,尤其是代码片段:

I'm a programmer coming from Python background which typically uses lexical scoping and I want to understand dynamic scope. I've researched it on-line, still unclear to me. For example, I've read this page which made things a lot easier to me, especially the code snippets:

#In Dynamic scoping:         
    const int b = 5;        
    int foo()               
    {                       
       int a = b + 5;
       return a;
    }

    int bar()
    {
       int b = 2;
       return foo();
    }

    int main()
    {
       foo(); // returns 10
       bar(); // returns 7
       return 0;
    }


#In lexical scoping:         
    const int b = 5;        
    int foo()               
    {                       
       int a = b + 5;
       return a;
    }

    int bar()
    {
       int b = 2;
       return foo();
    }

    int main()
    {
       foo(); // returns 10
       bar(); // returns 10
       return 0;
    }

据我所知,正如你所看到的,在动态范围内,bar 函数返回 7 而不是 10,这意味着 foo 调用了 bbar 中定义的变量,换句话说,foo 没有寻找在代码顶部定义的 b 变量(第一个 b 变量),而是使用了 bar 中定义的 b 变量.

As I understand and as you can see, in the dynamic scoping, bar function returns 7 not 10, which means foo called the b variable which is defined within bar, in other words, foo did not looked for the b variable that's defined in top of the code (the first b variable) but rather it used the b variables that's defined in bar.

Q1:因此,在动态作用域中,在这种情况下,在另一个函数中调用的函数 foobar 中调用首先在此中查找调用者函数中的变量case bar 然后它寻找顶级变量?

Q1: Hence, In dynamic scoping, the function that's being called within another function in this case foo called in bar first looks for variables in the caller function in this case bar and then it looks for top level variables ?

Q2:你能解释一下 Python 代码中的动态作用域吗?

Q2: Could you explain dynamic scoping in Python code ?

推荐答案

Python 中没有动态范围,除非您实现您自己的基于堆栈的命名空间".

There is no dynamic scoping in Python, unless you implement your own stack-based 'namespace'.

是的,动态范围就是这么简单;变量的值由最近的调用命名空间决定,其中设置了一个值.把调用看成一个栈,从上到下搜索当前的调用栈,找到一个值.

And yes, dynamic scoping is that simple; the value of a variable is determined by the closest calling namespace where a value was set. View the calls as a stack, and a value is looked up by searching the current call stack from top to bottom.

因此,对于您的动态示例,堆栈是第一位的:

So for your dynamic example, the stack is first:

foo
main 
globals -> b = 5

查找b = 5时在栈中搜索,然后栈变为

finding b = 5 when searching through the stack, and then the stack changes to

foo
bar -> b = 2
main
globals -> b = 5

所以 b = 2 找到了.

这篇关于如何使用 Python 代码理解动态范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆