最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

Python作用域用法实例详解

来源:懂视网 责编:小采 时间:2020-11-27 14:35:30
文档

Python作用域用法实例详解

Python作用域用法实例详解:本文实例分析了Python作用域用法。分享给大家供大家参考,具体如下: 每一个编程语言都有变量的作用域的概念,Python也不例外,以下是Python作用域的代码演示: def scope_test(): def do_local(): spam = local spam def do
推荐度:
导读Python作用域用法实例详解:本文实例分析了Python作用域用法。分享给大家供大家参考,具体如下: 每一个编程语言都有变量的作用域的概念,Python也不例外,以下是Python作用域的代码演示: def scope_test(): def do_local(): spam = local spam def do

本文实例分析了Python作用域用法。分享给大家供大家参考,具体如下:

每一个编程语言都有变量的作用域的概念,Python也不例外,以下是Python作用域的代码演示:

def scope_test():
 def do_local():
 spam = "local spam"
 def do_nonlocal():
 nonlocal spam
 spam = "nonlocal spam"
 def do_global():
 global spam
 spam = "global spam"
 spam = "test spam"
 do_local()
 print("After local assignment:", spam)
 do_nonlocal()
 print("After nonlocal assignment:", spam)
 do_global()
 print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

程序的输出结果:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

注意: local 赋值语句是无法改变 scope_test 的 spam 绑定。 nonlocal 赋值语句改变了 scope_test 的 spam 绑定,并且 global 赋值语句从模块级改变了 spam 绑定。

其中,nonlocal是Python 3新增的关键字。

你也可以看到在 global 赋值语句之前对 spam 是没有预先绑定的。

小结:

遇到在程序中访问全局变量并且要修改全局变量的值的情况可以使用:global关键字,在函数中声明此变量是全局变量

nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。

global关键字很好理解,其他语言大体也如此。这里再举一个nonlocal的例子:

def make_counter():
 count = 0
 def counter():
 nonlocal count
 count += 1
 return count
 return counter
def make_counter_test():
 mc = make_counter()
 print(mc())
 print(mc())
 print(mc())

运行结果:

1
2
3

转自:小谈博客 http://www.tantengvip.com/2015/05/python-scope/

希望本文所述对大家Python程序设计有所帮助。

文档

Python作用域用法实例详解

Python作用域用法实例详解:本文实例分析了Python作用域用法。分享给大家供大家参考,具体如下: 每一个编程语言都有变量的作用域的概念,Python也不例外,以下是Python作用域的代码演示: def scope_test(): def do_local(): spam = local spam def do
推荐度:
标签: 使用 例子 实例
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top