Python - 如何从函数中引用全局变量 [英] Python - How to reference a global variable from a function

查看:79
本文介绍了Python - 如何从函数中引用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定遗漏了一些关于 Python 变量范围的非常基本的概念,但我不知道是什么.

I must be missing some very basic concept about Python's variable's scopes, but I couldn't figure out what.

我正在编写一个简单的脚本,我想在其中访问在函数范围之外声明的变量:

I'm writing a simple script in which I would like to access a variable that is declared outside the scope of the function :

counter = 0

def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled()

出乎我的意料,跑步时我得到:

Unexpectedly for me, when running I get :

UnboundLocalError: local variable 'counter' referenced before assignment

在第一行添加全局声明

global counter
def howManyTimesAmICalled():
    counter += 1
    print(counter)

howManyTimesAmICalled() 

没有改变错误信息.

我做错了什么?正确的做法是什么?

What am I doing wrong? What is the right way to do it?

谢谢!

推荐答案

需要在函数定义中添加global counter.(不在代码的第一行)

You need to add global counter inside the function definition. (Not in the first line of your code)

你的代码应该是

counter = 0

def howManyTimesAmICalled():
    global counter
    counter += 1
    print(counter)

howManyTimesAmICalled()

这篇关于Python - 如何从函数中引用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆