云计算|云计算开发学习笔记:Python3 变量查找

来源 : 99API发布 : 2020-09-15 11:22:21访问数 : 2点赞数 : 1

  在Python3中查找变量的顺序为:“在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再去内置中找”。可以看一个具体的例子。

  Python 的一个内建值 int,我们首先将其赋值为 0,然后定义一个函数 fun1()。

686484538fe6450888309d2c429ecb51.png

  函数 fun1() 的作用就是调用函数 fun2() 来打印 int 的值。

  调用函数 fun1():

af05f211c7ab4c248362fd9a3e3f247c.png

  因为 local 中的 int = 2,函数将其打印出来。

  将函数 fun2() 中的 int = 2 删除:

b528c3cfba374123981a5c3648d0313d.png

  调用函数 fun1():

18941342718e434992dbf60dac09fc90.png

  因为 local 找不到 int 的值,就去上一层 non-local 寻找,发现 int = 1 并打印。

  而进一步删除函数 fun1() 中的 int = 1:

dd44d883aaf549c29acd986e83c670ba.png

  调用函数 fun1():

a4799bbf840e42b785cae160ad7b5889.png

  因为 local 和 non-local 都找不到 int 的值,便去 global 中寻找,发现 int = 0 并打印。

  若删除 int = 0这一条件:

db0c6a4dc6a94f37a34cba3cd8b05df9.png

  调用函数 fun1():

636474f369b441968f52745e1182b50e.png

  因为 local、non-local、global 中都没有 int 的值,便去 built-in 中寻找 int 的值,即:

618c63eee8b34e55964ecb5187c43908.png


1

电子邮箱:

service@99api.com

联系电话:

17350028402

微信客服:

电子邮箱:

service@99api.com

联系电话:

17350028402

微信客服: