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

全局变量在Python中可能导致不可预知性,降低函数和模块的通用性及代码可读性。然而,有时它们是必要的。介绍两种全局变量用法:声明法和模块法。遇到的问题是,在未正确声明全局变量时,尝试用列表实现栈操作导致错误。解决方案是在每个函数中声明全局变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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

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

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


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

1、声明法

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

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

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

def modifyConstant() :
        global CONSTANT
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT


2、模块法(推荐)

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

#gl.py
gl_1 = 'hello'
gl_2 = 'world'

在其它模块中使用
#a.py
import gl

def hello_world()
    print gl.gl_1, gl.gl_2

#b.py
import gl

def 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.py
plz input the initial stack :
123456
init stack successful !
['1', '2', '3', '4', '5', '6']
e is behalf exit stack operation
u is behalf stack push
p is behalf stack pop
v is behalf show stack
plz input what your order: 
u
input 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)

经运行检查,输出正确!



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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值