何时是使用和修改全局变量的适当时机?

2024-04-29 10:56:44 发布

您现在位置: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()  

Tags: andthermyoutruedo房间print
1条回答
网友
1楼 · 发布于 2024-04-29 10:56:44

不幸的是,许多教程(和教授)以简单的名义教授糟糕的代码(而且他们以后通常从不费心教正确的方法)。在这种情况下,直接执行顶级代码而不是将其放入main函数并在最后使用if __name__ == '__main__': main()这一事实加剧了问题。你知道吗

你应该尽量避免所有的全局状态会发生变异。可以声明常量,甚至不允许更改的列表/集合/dict。但其他所有内容都应该作为函数参数传递,或者作为某个类的self上的属性存储。你知道吗

如果没有其他问题,请考虑如何在存在可变全局变量的情况下编写单元测试(提示:这是不可能的)。你知道吗

要像您给定的那样转换代码,请缩进所有内容并添加标题class CryptGame:,将self作为每个函数的第一个参数,并用self.foo替换声明为global foo的所有变量。你知道吗

相关问题 更多 >