简体   繁体   English

无法使用python中的参数更改函数内部的全局变量

[英]can't change global variable inside function using parameter in python

import pickle
    
    name = 'something'
    
    def save(variable, value):
        obj = str(value)
        file = f'{variable}.pkl'
        fileObj = open(file, 'wb')
        pickle.dump(obj, fileObj)
        global variable
        variable = value
        fileObj.close()
    
    def read(variable):
        file = f'{variable}.pkl'
        with open(file, 'rb') as oFile:
            content = pickle.load(oFile)
            print(content)
            oFile.close()
    
    save(name, 'else')
    print('!! > ',name)
    read(name)

Error: File "h:/PythonProjects/Python.py", line 10 global variable SyntaxError: name 'variable' is used prior to global declaration错误:文件“h:/PythonProjects/Python.py”,第 10 行全局变量 SyntaxError:在全局声明之前使用了名称“变量”

any suggestions about how to change global variable with a parameter?关于如何使用参数更改全局变量的任何建议?

Before using the global statement, you need to define a global variable...在使用 global 语句之前,您需要定义一个全局变量...

variable = None

def bla():
    global variable
    variable = 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM