Python Global Variables - Not Defined?

前端 未结 2 830
死守一世寂寞
死守一世寂寞 2021-01-20 20:39

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

2条回答
  •  深忆病人
    2021-01-20 20:53

    You have to use the global keyword inside the function rather than outside. All the df that you have defined inside your function are locally scoped. Here is the right way -

    df = pd.DataFrame() # No need to use global here
    
    def __init__(self, master):
        global df # declare here
        df = None
    ....
    
    def load(self):
        global df # declare here
        ....
        df = pd.read_csv(filepath)
    
    def save(self):
        global df # declare here
        ....
        df = df.append(...)
    

提交回复
热议问题