【问题标题】:Python: Global Variables From Within Functions + CursesPython:来自函数内部的全局变量 + 诅咒
【发布时间】:2011-07-06 17:38:36
【问题描述】:

我很困惑……

基本上试图声明一个指向curses窗口的全局变量,这样我就可以使用调试命令,但是它抱怨AttributeError: 'NoneType' object has no attribute 'addstr'这意味着它没有被设置?请帮忙!

wDebug = None

def start(stdscr):
    curses.nocbreak()
    curses.echo()
    screenSize = stdscr.getmaxyx()

    wDebug = curses.newwin(5, screenSize[1], 0, 0);

    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)

    wDebug.bkgd(curses.color_pair(1))
    wDebug.refresh()

    /* Snip */

    awaitInput(wInput)

    while 1: pass

def awaitInput(window): 
  while 1:
    msg = /* Snip */
    sendMessage(msg)

def sendMessage(msg):
  /* Snip */
  debug("Send message")

def debug(msg):
  wDebug.addstr(msg + "\n")
  wDebug.refresh()  

非常感谢您的宝贵时间,

【问题讨论】:

    标签: python curses


    【解决方案1】:

    您需要使用global statement:

    wDebug = None
    
    def start(stdscr):
        global wDebug
        #...
        wDebug = curses.newwin(5, screenSize[1], 0, 0);
    

    来自文档:

    没有global就不可能分配给全局变量

    【讨论】:

    • 哦,不知道你必须在 Python 中执行此操作,noob 错误,谢谢!
    • 那你怎么能在debug中访问全局变量呢?
    • @Pez:在 Python 中,变量默认是本地的。当您访问未在函数中分配的变量时,Python 将检查全局变量。但是,如果您分配给任何变量,Python 会认为它必须是局部变量,除非您明确说明(即使存在该名称的全局变量)。像 def foo(): x += 10 这样的函数会引发 UnboundLocalError,即使有一个名为 x 的全局变量(注意错误的名称)。
    • 感谢您的解释!我想我需要买一本关于 python 的书,只是阅读随机教程意味着我错过了这样的概念!
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2020-04-04
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2014-04-23
    相关资源
    最近更新 更多