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

2024-10-03 23:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在python函数中,我希望对函数中的全局变量使用(读取、查询(if语句检查),然后执行其他语句)。 要在函数中执行此操作,我必须将变量声明为全局变量。 我想给函数传递一个变量,然后使用传递的变量将正确的全局变量声明为全局变量。在

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")

如有任何帮助,我们将不胜感激:)


Tags: 函数name声明dataleniflocal语句
2条回答

不需要在函数中创建全局状态变量;只需更改其值

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]

休的评论是对的,但如果你还想这么做,你可以:

exec('global ' + var_name_from_list)

请参见Python3.6的文档here

编辑

对于Python2.7,请参见here

相关问题 更多 >