python 变量作用域

一、同文件下全局变量使用规则 

x = 10
def fun1():
    print(x)
def fun2():
    x += 13
    print(x)
   
fun1()
fun2()

运行结果:
10
Traceback (most recent call last):
  File "G:\study\JAVA\python_test1\locust\test\test_mine.py", line 16, in 
    fun2()
  File "G:\study\JAVA\python_test1\locust\test\test_mine.py", line 12, in fun2
    x += 13
UnboundLocalError: local variable 'x' referenced before assignment

针对上面的问题,我们先来看一下,对局部变量和全局变量的隐式规则:

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the globaldeclaration for identifying side-effects.

大概意思:如果一个仅在函数内引用变量,则该变量暗指全局变量。如果函数内对变量进行赋值,除非该变量声明为全局变量,否则该变量只是局部变量。

现在看上面的报错就明白的多了,fun1函数内只是引用了变量x,所以暗指x为全局变量,会在当前文件中搜索变量x;而fun2对变量x直接做自加运算,而x有没有在函数内声明,所以会报错。

二、跨模块使用全局变量

config.py 文件中声明全局变量 x = 0

mod.py文件中引用x,并修改其值

import config

config.x += 1

然后main.py文件中引用config和mod,并输出x的值

import config

import mod

print(config.x)

运行结果:1

 

你可能感兴趣的:(python,全局变量,局部变量)