何时适合使用和修改全局变量?

时间:2014-10-02 01:49:31

标签: python

我想开始我是编程的新手。我从来没有上过任何课程。我刚刚决定听起来很有意思并尝试一下。

无论如何,我一直在网上阅读“学习Python困难之路”,并且已经练习了36次。这个练习涉及制作我自己的基于文本的游戏。现在,对于这个问题。何时适合使用和修改全局变量?我刚刚开始冒险,想要在其他事件发生之前添加玩家必须做的事情,例如在第一个房间的大门打开之前在另一个房间拉一个杠杆。如果玩家希望稍后返回第一个房间,则仍会触发门和杠杆。

到目前为止,这是代码。请注意,它没有充实。只是想知道它是否有效。

print "You are a lone adventurer with the bounty to clear out the crypt."
print "You come with nothing but your sword and a compass."
print "You enter the crypt."
print "To the north you have a gated portaculas and rooms to the west and east."
print "What do you do?"

gate = False
lever = False
def entrance():
    global gate

    while True:
        choice = raw_input('> ')

        if choice == 'west':
            guard_shack()
        elif choice == 'east':
            lever_rm()
        elif choice == 'north' and gate == False:
            print "The gate is still closed and locked."
            entrance()
        elif choice == 'north' and gate == True:
            fountain_rm()
        else:
            entrance(gate)

def lever_rm():
    global lever
    global gate

    print "You enter the room."
    print "What do you do"

    while True:
        choice = raw_input('> ')

        if 'search' in choice:
            print "You look around the room and notice a lever on the opposite wall."
        elif "pull lever" in choice:
            print "You pull the lever."
            lever = True
            gate = True
        elif choice == 'west':
            entrance()
        else:
            print '> '

def fountain_rm():
    print "you're in the lever room!"
entrance()  

1 个答案:

答案 0 :(得分:0)

不幸的是,许多教程(和教授)以简单的名义教授不良代码(他们通常从不打扰以后教授正确的方法)。在这种情况下,由于您直接执行顶级代码而不是将其放在main函数中并在最后使用if __name__ == '__main__': main(),因此问题更加严重。

您应该尝试避免可以变异的所有全局状态。可以声明常量,甚至是不允许更改的列表/设置/字符串。但是其他所有内容都应该作为函数参数传递,或者作为属性存储在某个类的self上。

如果不出意外,请考虑如何在存在可变全局变量的情况下编写单元测试(提示:这是不可能的)。

要转换您已经给出的代码,缩进所有内容并添加标题class CryptGame:,添加self作为每个函数的第一个参数,并替换所有声明为global foo的变量与self.foo