Python作用域用法实例详解

WBOY
Release: 2016-06-10 15:05:49
Original
1115 people have browsed it

本文实例分析了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)

Copy after login

程序的输出结果:

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

Copy after login

注意: 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())

Copy after login

运行结果:

1
2
3

Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!