简体   繁体   English

一个(可能的)Python作用域问题

[英]A (possible) Python scope issue

I cannot contribute my actual code (because it's over ten thousand lines), but I can give a brief summary of it. 我不能提供我的实际代码(因为它超过一万行),但是我可以对其做一个简短的总结。 Here it is, I give the symptoms later: 在这里,我稍后给出症状:

def calculate_stuffs():
    *global lots of stuff*
    *some other stuff*
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSLASH:
                try:
                    exec easygui.enterbox('Type command:')
                except:
                    print "Command crashed, or Easygui is not installed."
    *a lot of other stuff*

Here are some examples of when it works/fails: 以下是一些工作/失败时的示例:

  • If I type a command that doesn't work, it returns the appropriate message. 如果我输入的命令无效,它将返回相应的消息。

  • If I tell it to run a function, it works. 如果我告诉它运行一个函数,它将起作用。

  • If I tell it to read a variable (eg print a variable) it works. 如果我告诉它读取一个变量(例如打印一个变量),它将起作用。

  • If I tell it to write to a variable, it doesn't do anything. 如果我告诉它写入变量,它不会执行任何操作。 It doesn't even give the crashing message. 它甚至没有给出崩溃的消息。 I made xa global variable, and it still does nothing if I say something like "x += 5". 我做了xa全局变量,如果我说“ x + = 5”,它仍然不起作用。

I'm pretty sure this is an issue with scope, but I'm not sure. 我很确定这是范围问题,但是我不确定。

If you need me to contribute more code, just ask. 如果您需要我提供更多代码,请询问。 When you find the answer, please explain why it works. 找到答案后,请说明原因。 Thank you! 谢谢!

You need to use global within the exec statement as well, as exec has its own scope like a function: 您还需要在exec语句中使用global ,因为exec具有像函数一样的作用域:

x = 10

def foo():
    global x
    command = 'global x; x += 1; print x'
    try:
        exec command
    except:
        print "error"

print x
foo()
print x

will print: 将打印:

10
11
11

Without global x within the exec statement it would print: 如果在exec语句中没有global x ,它将打印:

10
11
10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM