首先,函数里面是可以访问外部变量的

#scope.py
def scope_test():
spam = 'scope_test spam'
def inner_scope_test():
spam = 'inner_scope_test spam'
def do_local():
spam = 'local spam'
def do_nonlocal():
nonlocal spam
spam = 'nonlocal spam'
def do_global():
global spam
spam = 'global spam'
do_local()
print('after local assignment:', spam)
do_nonlocal()
print('after nonlocal assignment:', spam)
do_global()
print('after global assignment', spam)
inner_scope_test()
print('after inner_scope_test:', spam)

进行如下操作

>>> import scope
>>> scope.scope_test();\
... print(scope.spam)
after local assignment: inner_scope_test spam
after nonlocal assignment: nonlocal spam
after global assignment nonlocal spam
after inner_scope_test: scope_test spam
global spam
>>> print(spam)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
  • do_local() 对本地变量操作,并未影响外部变量
  • do_nonlocal() 似乎是对外一层的 spam 进行了操作
  • do_global() 则是对 scope.spam 进行了操作
  • 同时可以发现 spam 未定义,这是因为 function 的 global 是相对于其定义所在的模块而言的,官方文档叙述如下

    It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called.

若进行如下操作

>>> from scope import scope_test as f
>>> f()
after local assignment: inner_scope_test spam
after nonlocal assignment: nonlocal spam
after global assignment nonlocal spam
after inner_scope_test: scope_test spam
>>> print(spam)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> import scope
>>> scope.spam
'global spam'

可见即使只 from scope import scope_test as f ,执行  f() 当前命名空间仍然没有 spam ,甚至若在此时导入 scope 模块, 会发现存在 scope.spam , 可见对 f() 而言,global 仍然是相对于 scope 而言的,即使 执行 f() 时 scope 模块并没有导入,为了证明 spam 确实是在执行 f()  时才被引入的,贴上下面的代码

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scope
>>> scope.spam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'scope' has no attribute 'spam'

还有一种情况需要说明,看下面代码

def scope_test():
spam = 'scope_test spam'
def inner_scope_test():
spam = 'inner_scope_test spam'
def do_local():
##############
print(spam)
spam = 'local spam'
##############
def do_nonlocal():
nonlocal spam
spam = 'nonlocal spam'
def do_global():
global spam
spam = 'global spam'
do_local()
print('after local assignment:', spam)
do_nonlocal()
print('after nonlocal assignment:', spam)
do_global()
print('after global assignment', spam)
inner_scope_test()
print('after inner_scope_test:', spam)

注意区别仅在于 do_local() 函数中,在  spam = 'local spam' 前面加了一句 print(spam) ,本以为 spam 会先输出外部变量,再对本地变量赋值,但事实上被视为语法错误------先使用后定义错误

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.
>>> import scope
>>> scope.scope_test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\Coding\Python\scope.py", line 21, in scope_test
inner_scope_test()
File "E:\Coding\Python\scope.py", line 15, in inner_scope_test
do_local()
File "E:\Coding\Python\scope.py", line 7, in do_local
print(spam)
UnboundLocalError: local variable 'spam' referenced before assignment

Python学习小记(3)---scope&namespace的更多相关文章

  1. Python学习小记(1)---import小记

    在这种目录结构下,import fibo会实际导入fibo文件夹这个module λ tree /F 卷 Programs 的文件夹 PATH 列表 卷序列号为 BC56-3256 D:. │ fib ...

  2. python学习小记

    python HTTP请求示例: # coding=utf-8 # more materials: http://docs.python-requests.org/zh_CN/latest/user/ ...

  3. Python学习小记(5)---Magic Method

    具体见The Python Language Reference 与Attribute相关的有 __get__ __set__ __getattribute__ __getattr__ __setat ...

  4. Python学习小记(4)---class

    1.名称修改机制 大概是会对形如 __parm 的成员修改为 _classname__spam 9.6. Private Variables “Private” instance variables ...

  5. Python学习小记(2)---[list, iterator, and, or, zip, dict.keys]

    1.List行为 可以用 alist[:] 相当于 alist.copy() ,可以创建一个 alist 的 shallo copy,但是直接对 alist[:] 操作却会直接操作 alist 对象 ...

  6. python 学习小记之冒泡排序

    lst =[11,22,44,2,1,5,7,8,3] for i in range(len(lst)):     i = 0     while i < len(lst)-1:         ...

  7. Python学习 Part7:类

    Python学习 Part7:类 1. 作用域和命名空间 命名空间(namespace)就是一个从名称到对象的映射. 命名空间的一些实例:内置名称集(函数,像abs(),和内置异常名称),一个模块中的 ...

  8. mongodb入门学习小记

    Mongodb 简单入门(个人学习小记) 1.安装并注册成服务:(示例) E:\DevTools\mongodb3.2.6\bin>mongod.exe --bind_ip 127.0.0.1 ...

  9. python学习笔记之module && package

    个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...

随机推荐

  1. 【javaScript】获取某年某月的的最后一天(即当月天数) 妙用

    javaScript里 面的new Date("xxxx/xx/xx")这个日期的构造方法有一个妙处,当你传入的是"xxxx/xx/0"(0号)的话,得到的日期 ...

  2. CentOS 6.6 下源码编译安装MySQL 5.7.5

    版权声明:转自:http://www.linuxidc.com/Linux/2015-08/121667.htm 说明:CentOS 6.6 下源码编译安装MySQL 5.7.5 1. 安装相关工具# ...

  3. 机器学习李航——Adaboost课本例题实现

    例8.1Adaboost的例子 注意求D3或者D4的时候只需要把w替换一下就行,记得还得改阈值.这个代码算个半自动的,因为还需要手动改一下. import numpy as np def getA(e ...

  4. STM8 关闭PWM输出后的电平输出问题解决

    STM系列的单片机PWM输出如果被关断比如用TIM1_CtrlPWMOutputs进行停止输出后,电平的高低处于不确定的状态. 他取决于: 1.GPIO初始化的特性 2.关断那一刻时的电平 3.CCM ...

  5. 使用RKE快速部署k8s集群

    一.环境准备 1.1环境信息 IP地址 角色 部署软件 10.10.100.5 K8s Master Etcd.Control 10.10.100.17 K8s Worker1 Worker 10.1 ...

  6. 源码分析系列 | 从零开始写MVC框架

    1. 前言 2. 为什么要自己手写框架 3. 简单MVC框架设计思路 4. 课程目标 5. 编码实战 5.1 配置阶段 web.xml配置 config.properties 自定义注解 5.2 初始 ...

  7. ubuntu+mysql+php+apache2+wordpress建站全记录

    虽然操作并不难,但用到的各种命令,各种坑的解决方法还需要记一下 建好的博客: 念诗之人的博客 VPS和域名选购 VPS选购 国内外有很多商家可供选择,国内有如阿里云,百度云,腾讯云等(ECS,BCC等 ...

  8. 【MySQL 原理分析】之 Trace 分析 order by 的索引原理

    一.背景 昨天早上,交流群有一位同学提出了一个问题.看下图: 我不是大佬,而且当时我自己的想法也只是猜测,所以并没有回复那位同学,只是接下来自己做了一个测试验证一下. 他只简单了说了一句话,就是同样的 ...

  9. Idea使用插件实现逆向工程搭建SpringBoot项目

    之前写SpringBoot项目,每次都要手动去写实体类.dao层啥的,尤其是数据库表字段特别多的时候,特别麻烦.然后很多小伙伴都会用逆向工程来自动生成这些类,省去许多没必要的代码量,但是Mybatis ...

  10. 一文读懂什么是一致性hash算法

    Hash,一般翻译做散列.杂凑,或音译为哈希,是把任意长度的输入通过散列算法变换成固定长度的输出,该输出就是散列值.这种转换是一种压缩映射,也就是,散列值的空间通常远小于输入值的空间,不同的输入可能会 ...