---
title: "Python中的全局变量"
author: "fudehai001"
date: "2009-07-21T14:34:33Z"
tags: []
slug: "python"
draft: false
lastmod: "2009-07-21T14:34:33Z"
id: 430049
url: "https://laozy.iteye.com/blog/430049"
---

全局变量不符合参数传递的精神，所以，平时我很少使用，除非定义常量。今天有同事问一个关于全局变量的问题，才发现其中原来还有门道。

程序大致是这样的：

CONSTANT = 0

def modifyConstant() :
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

运行结果如下：
UnboundLocalError: local variable 'CONSTANT' referenced before assignment

看来，全局变量在函数modifyConstant中边成了局部变量，似乎全局变量没有生效？
做点修改：

CONSTANT = 0

def modifyConstant() :
        print CONSTANT
        ＃CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

运行正常，看来函数内部是可以访问全局变量的。
所以，问题就在于，因为在函数内部修改了变量CONSTANT，Python认为CONSTANT是局部变量，而print CONSTANT又在CONSTANT += 1之前，所以当然会发生这种错误。

那么，应该如何在函数内部访问并修改全局变量呢？应该使用关键字global来修饰变量（有点像PHP）：

CONSTANT = 0

def modifyConstant() :
        global CONSTANT
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

就这么简单！