名称错误:未定义全局名称“thing”

2024-09-20 22:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我不认为有必要继续投票,我只是想在这里学习!

一个.py

from two import *

ADooDah = Doodah()
something = Thing(ADooDah)

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

2.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和关于隐式类型和作用域的规则还比较陌生,我还在学习中!

不过,我已经解决了我的问题。谢谢。事实证明,这与上述情况完全无关。


Tags: pyselfidtruereturnifvardef
3条回答
Something = Thing(ADooDah)

thing.DoThis()

你的thing称为Something。 此外,类Thing没有您正在调用/未调用的任何方法(缺少paren)。这几乎是无意义的代码。

我给出以下代码。

我不知道他们会用什么。。。。。。但他们能跑。

是的。

2.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'

是的。

一个.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

有几个问题:

你声称Thing是在Two.py中定义的。如果是,则需要导入它:

from Two import Thing

或(不推荐):

from Two import *

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

接下来,您需要定义thing,这是您尚未定义的。我猜你想让thing成为Thing对象:

thing = Thing(ADooDah)

然后就是有人在评论中提到的if内部HasDoneStuff的pf问题,以及Thing不完整的事实(在另一个答案中也提到)。

相关问题 更多 >

    热门问题