关于Python中全局变量的使用的调试

来源:互联网 发布:达芬奇调色软件12.5 编辑:程序博客网 时间:2024/06/05 08:05

首先啰嗦一段全局变量的使用方法:


应该尽量避免使用全局变量。不同的模块都可以自由的访问全局变量,可能会导致全局变量的不可预知性。对全局变量,如果程序员甲修改了_a的值,程序员乙同时也要使用_a,这时可能导致程序中的错误。这种错误是很难发现和更正的。 

全局变量降低了函数或模块之间的通用性,不同的函数或模块都要依赖于全局变量。同样,全局变量降低了代码的可读性,阅读者可能并不知道调用的某个变量是全局变量。

但是某些时候,全局变量能够解决局部变量所难以解决的问题。事物要一分为二。


python里面全局变量有两种灵活的用法:

1、声明法

在文件开头声明全局变量variable,

在具体函数中使用该变量时,需要事先声明 global variable,否则系统将该变量视为局部变量。

CONSTANT = 0 (将全局变量大写便于识别)

def modifyConstant() :        global CONSTANT        print CONSTANT        CONSTANT += 1        returnif __name__ == '__main__' :        modifyConstant()        print CONSTANT


2、模块法(推荐)

把全局变量定义在一个单独的模块中:

#gl.pygl_1 = 'hello'gl_2 = 'world'

在其它模块中使用
#a.pyimport gldef hello_world()    print gl.gl_1, gl.gl_2#b.pyimport gldef fun1()    gl.gl_1 = 'Hello'    gl.gl_2 = 'World'


第二种方法,适用于不同文件之间的变量共享,而且一定程度上避免了开头所说的全局变量的弊端,推荐!


下面是我使用时自己遇到的一个小问题,我自己想用列表实现一个栈的操作:

#---!---coding=utf-8__author__ = 'Itachi'#---定义全局栈列表stack = []#---初始化栈def initStack():    stack = list(input('plz input the initial stack :\n'))    if(len(stack) == 0):        print('It is a empty stack, are you sure ?')    else:        print('init stack successful !')        print(stack)#---压栈def push():    pushElement = input('input what you want to push in stack:\n')    print(stack)    if(stack.append(pushElement) == None):        print('push succedssful !')        print(stack)    else:        print('push error !')#---出栈def pop():    if(len(stack) == 0):        print('stack is empty !')    else:        popElement = stack.pop()        print('pop element is ', popElement)#---栈操作def stackOperation():    while True:        order = input('plz input what your order: \n')        if order == 'u':            push()        elif order == 'p':            pop()        elif order == 'v':            print('Now stack is: ', stack)        elif order == 'e':            break        else:            print('can not recognize order !')#---显示栈操作提示def showOrder():    orderDict = {'u':'stack push','p':'stack pop','v':'show stack','e':'exit stack operation'}    for key,value in orderDict.items():        print('%s is behalf %s' %(key, value))#----主程序if __name__ == '__main__':    initStack()    showOrder()    stackOperation()

但是输出总是存在问题,存放栈的列表不能全局:

D:\Python34\python.exe D:/PycharmProjects/Test/ListToStack.pyplz input the initial stack :123456init stack successful !['1', '2', '3', '4', '5', '6']e is behalf exit stack operationu is behalf stack pushp is behalf stack popv is behalf show stackplz input what your order: uinput what you want to push in stack:0[]push succedssful !['0']plz input what your order: 



检查发现,必须在每个使用全局列表中都先声明这个全局变量,不然就默认为函数内的局部变量,所以将函数操作修改代码如下:

#---初始化栈def initStack():    stack = list(input('plz input the initial stack :\n'))    <span style="color:#FF0000;"><strong>global stack</strong></span>    if(len(stack) == 0):        print('It is a empty stack, are you sure ?')    else:        print('init stack successful !')        print(stack)#---压栈def push():    pushElement = input('input what you want to push in stack:\n')    <span style="color:#FF0000;"><strong>global stack</strong></span>    print(stack)    if(stack.append(pushElement) == None):        print('push succedssful !')        print(stack)    else:        print('push error !')#---出栈def pop():    <span style="color:#FF0000;"><strong>global stack</strong></span>    if(len(stack) == 0):        print('stack is empty !')    else:        popElement = stack.pop()        print('pop element is ', popElement)

经运行检查,输出正确!



上面只是我自己出的一些低级问题,新手可能需要注意一下。


0 0
原创粉丝点击