Python全局变量-未定义? [英] Python Global Variables - Not Defined?

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

问题描述

我遇到了一个问题,在2个不同的函数中修改了全局变量后,该变量没有被记住。变量 df 应该是一个数据框,在用户加载正确的文件之前,它不会指向任何内容。这类似于我所拥有的东西(使用 pandas tkinter ):

I'm running into an issue where a global variable isn't "remembered" after it's modified in 2 different functions. The variable df is supposed to be a data frame, and it doesn't point to anything until the user loads in the right file. This is similar to something I have (using pandas and tkinter):

global df

class World:

    def __init__(self, master):
        df = None
        ....

    def load(self):
        ....
        df = pd.read_csv(filepath)

    def save(self):
        ....
        df = df.append(...)

save()总是在 load()之后调用。问题是,当我调用 save()时,出现错误消息未定义 df 。我以为 df init()中得到了初始赋值,然后在 load()?我在这里做什么错了?

save() is always called after load(). Thing is, when I call save(), I get the error that "df is not defined." I thought df got its initial assignment in init(), and then got "updated" in load()? What am I doing wrong here?

推荐答案

您必须使用 global df inside 需要修改全局变量的函数。否则(如果要写入),您将在函数内部创建一个具有相同名称的局部范围的变量,而您的更改将不会反映到全局变量中。

Yo have to use global df inside the function that needs to modify the global variable. Else (if writing to it) you are creating a local scoped variable of the same name inside the function and your changes wont be reflected to the global one.

p = "bla"

def func():
    print("print from func:", p)      # works, readonly access, prints global one

def func1():
    try: 
        print("print from func:", p)  # error, python does not know you mean the global one
        p = 22                        # because function overrides global with local name   
    except UnboundLocalError as unb:
        print(unb)

def func2():
    global p
    p = "blubb"                       # modifies the global p

print(p)
func()
func1()
print(p)
func2()
print(p)

输出:

bla   # global

print from func: bla    # readonly global

local variable 'p' referenced before assignment  # same named local var confusion

bla    # global
blubb  # changed global

这篇关于Python全局变量-未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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