---
title: "global语句局部与全局变量"
author: "saber7"
date: "2010-12-04T22:43:31Z"
tags: ["Python", "编程"]
categories: ["编程语言"]
slug: "global"
draft: false
lastmod: "2010-12-04T22:43:31Z"
id: 833603
url: "https://saber7.iteye.com/blog/833603"
---

很好理解，global语句是为了声明在函数内定义的一个变量不是局部的而是全局的。

 

```
#-*-coding=gbk
def gl(x):
    print x# 第一次输出时使用形参变量x = 1
    x = 0# 为x赋值 x = 0(局部)
    print x# 此时输出局部变量

x = 1
gl(x)
print x# 验证函数外主块中x没受影响
```

 输出：

&gt;&gt;&gt;  
1  
0  
1

 

```
#-*-coding=gbk
def gl():
    global x# 声明x变量不是局部的，而是全局的

    print x
    x = 0
    print x

x = 1
gl()
print x
```

 输出：

1  
0  
0

 

下面是《python核心编程》里的例子：

```
#-*-coding=gbk
is_this_global = 'xyz'
def foo():
    global is_this_global
    this_is_local = 'abc'
    is_this_global = 'def'
    print this_is_local + is_this_global
foo()
print is_this_global# 这里验证is_this_global得到的是函数内赋值的def
```

输出：

&gt;&gt;&gt;  
abcdef  
def