0

我正在学习 python,并且遇到了全局变量/列表的问题。我正在编写一个基本的河内手动塔程序,这是目前的程序:

pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]

def tower_of_hanoi():

    global pillar1
    global pillar2
    global pillar3

    print_info()

def print_info():

    global pillar1
    global pillar2
    global pillar3

    for i in range(4,-1,-1):
        print(pillar1[i], " ", pillar2[i], " ", pillar3[i])

我尝试了一些变体,但每次我收到错误“NameError:未定义全局名称'pillar1'”。

在此设置中处理全局列表的最佳方法是什么?如果可能的话,我宁愿只使用一个源文件。谢谢!

4

2 回答 2

13

这是因为您已将其“声明”为pilar1,而不是pillar1

于 2013-01-18T15:51:45.063 回答
6

您遇到的问题pilarpillar. 修复该问题后,您将不再需要global声明:

pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]

def tower_of_hanoi():    
    print_info()

def print_info():    
    for i in range(4,-1,-1):
        print(pillar1[i], " ", pillar2[i], " ", pillar3[i])

只有在非全局范围内分配全局变量时才需要使用 global,例如函数定义:

# global variable, can be used anywhere within the file since it's
# declared in the global scope
my_int = 5

def init_list():
    # global variable, can be used anywhere within the file after
    # init_list gets called, since it's declared with "global" keyword
    global my_list
    my_list = [1, 2, 3]

def my_function():
    # local variable, can be used only within my_function's scope
    my_str = "hello"

    # init's global "my_list" variable here, which can then be used anywhere
    init_list()
    my_list.append(5)

my_function()
print(my_list)

但是,您不应过多地使用全局变量,而应使用函数参数来传递值。

于 2013-01-18T15:55:29.620 回答