zoukankan      html  css  js  c++  java
  • Python Variable Scope

      Python中的变量的作用域有时会让像我这样的初学者很头疼。

      其实只需要掌握以下两点:  

      1. Python能够改变变量作用域的代码段是def、class、lamda;

          而if/elif/else、try/except/finally、for/while 并不能更改变量作用域. 示例略

      2. 变量搜索路径是:本地变量 -> 上层变量

        示例如下:

    def accessOut():
        print(outVar)
    
    outVar = 10
    accessOut()

      在上例中,def改变了变量的作用域. 当执行print(outVar)时, 当前层中没有找到变量outVar的定义, 所以到上一层中找, 找到了, 所以就

    用这一层的outVar(值为10).当然如果在这一层中也没有找到outVar,那么就要继续到上一层中查找.

      如果你感觉这篇文章写得太简略了,你可以参照这里,讲得很详细.

      通过一个例子来进一步理解:

    #!/usr/bin/python2.7
    #File: demo.py
    #Author: lxw
    #Time: 2014-09-01
    
    number = 5
    def func0():
        #It's OK to reference.
        print number
    
    def func1():
        #new local variable.
        number = 10
        print number
    
    def func2():
        #global declaration.
        global number
        print number
        number = 10
        print number
    
    print "Before calling any function, number is {}".format(number)
    print "Calling func0()----------"
    func0()
    print "Calling func1()----------"
    func1()
    print "After calling func1(), number is {}".format(number)
    print "Calling func2()----------"
    func2()
    print "After calling func2(), number is {}".format(number)

    Output:

    lxw@ubuntu:~/Python/Practice$ python demo.py 
    Before calling any function, number is 5
    Calling func0()----------
    5
    Calling func1()----------
    10
    After calling func1(), number is 5
    Calling func2()----------
    5
    10
    After calling func2(), number is 10

    注意: 如果将func1改成下面的形式(注意与func0的对比):

    def func1():
        #new local variable.
        print number
        number = 10
        print number

      就会出现下面的错误提示: 

      UnboundLocalError: local variable 'number' referenced before assignment

      在python2.7 和 python3.4上测试, 出现同样的上述结果.

  • 相关阅读:
    Scrum敏捷开发中的各种会议到底怎么开?
    敏捷的方法与误区
    原创:分享封装好的面向JAVA的memcached客户端操作类
    ReactRouter路由配置
    脚手架创建react项目
    React基础知识
    Fetch请求
    redux学习笔记
    npm install常用用法
    python3+selenium3自动化8——当click事件失效,如何解决 测试
  • 原文地址:https://www.cnblogs.com/lxw0109/p/Python-Variable-Scope.html
Copyright © 2011-2022 走看看