在python中的函数内从传递的变量声明全局变量

时间:2017-09-09 01:30:55

标签: python python-2.7 function global-variables local-variables

在我的python函数中,我想在函数内的全局变量上使用(读取,查询(如果是语句检查),然后执行其他语句)。 要在函数内执行此操作,我必须将变量声明为全局变量。 我想将函数传递给变量,然后使用传递的变量将正确的全局变量声明为全局变量。

current_data_list = []
current_data_list_length = len(current_data_list)

#the list is filled with each line from a file

def listtousable(listname):
    local_list_name = listname
    local_list_length = local_list_name + "_length"

    global local_list_name
    global local_list_length

    if local_list_name[0] == "firstlinevariable":
        local_list_length = len(local_list_name)
        print local_list_length
    else:
        print "wtf"
#fill into list
listtousable("current_data_list")

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

休的评论是正确的,但如果你仍然想这样做,你可以:

exec('global ' + var_name_from_list)

请参阅文档here了解python 3.6

修改

对于python 2.7,请参阅here

答案 1 :(得分:0)

您不需要在函数中创建全局状态var;你可以改变它的价值,

program_state = "processing"

state_files = {
    "loading":    "loading.txt",
    "filtering":  "filtered.txt",
    "processing": "process_data.txt",
    "done":       "final.txt"
}

def processing_function(data):
    global program_state
    program_state = "processing"
    output_file = state_files[program_state]
相关问题