NameError: 全局名 'thing' 未定义

-2 投票
3 回答
9520 浏览
提问于 2025-04-16 22:16

我觉得继续被投反对票没必要,我只是想在这里学习而已!

One.py

from two import *

ADooDah = Doodah()
something = Thing(ADooDah)

something.DoThis()
something.DoThat
something.DoAnother
if (something.has_done_stuff() == True)
    self.SomeFunction

Two.py

class Thing(var):
    def __init__(self, var)
        self.SomeVar = var

    def has_done_stuff(self):
        while True:
            id, newMessage = SomeVar.get_next_message()
            if id == 0:
                return true
            else:
                return false

我明白了...

Traceback (most recent call last):
  File "C:\One.py", line 9, in <module>
    has_done_stuff = thing.HasDoneStuff()
NameError: global name 'thing' is not defined

补充说明:代码确实有很多错误。我只是想展示我的情况,而不是一些真正的代码。匆忙打字导致了很多低级错误。其实我也不是那么糟糕!大部分时候是这样 ;) 。

我希望这些补充说明能让事情更清楚,你们能停止关注那些疯狂的语法错误,能多解释一下我可能遇到的作用域问题。我对Python/IronPython还比较陌生,关于隐式类型和作用域的规则我还在学习中!

不过我已经解决了我的问题。谢谢。结果发现这和上面提到的没什么关系。

3 个回答

2

这里有几个问题:

你说 Thing 是在 Two.py 里定义的。如果是这样,你需要这样导入它:

from Two import Thing

或者(不推荐这样做):

from Two import *

接下来,你需要用 class,而不是 Class

然后,你需要定义 thing,但你还没有这样做。我猜测你想让 thing 成为一个 Thing 对象:

thing = Thing(ADooDah)

还有一个问题是关于 HasDoneStuff 里面的 if,有人在评论中提到过,以及 Thing 还不完整(在另一个回答中也提到过)。

3
Something = Thing(ADooDah)

thing.DoThis()

你的thing叫做Something。另外,你的类Thing里面没有你正在调用或者没有调用的方法(缺少括号)。这段代码基本上是没什么意义的。

1

我给出以下代码。

我不知道它们能用来做什么……但它们是可以运行的。

.

two.py

from time import time

class Thing():
    def __init__(self, var):
        self.SomeVar = enumerate(var)

    def HasDoneStuff(self):
        while True:
            id, newMessage = self.SomeVar.next()
            print newMessage
            print 'id==',id
            return id == 0

    def DoThis(self):
        print "DoThis' result"

    def DoThat(self):
        print 'DoingThat ;;;;;;;;;;;;;;;;;;;;;'

    def DoAnother(self):
        print 'DoAnother time',time()

    def SomeFunction(self):
        print 'Humpty Dumpty sat on a wall'

.

one.py

from two import *


def Doodah(ss):
    return ss.split()

ADooDah = Doodah('once upon a time')

Something = Thing(ADooDah)


Something.DoThis()
Something.DoThat()
Something.DoAnother()

print '\n==========================\n'

while True:
    try:
        if Something.HasDoneStuff():
            Something.SomeFunction()
        print '---------------'
    except StopIteration:
        print "That's all folks"
        break

撰写回答