NameError: name is not defined in python init function

NameError: name is not defined in python init function

class HumidityServer(CoAP):
    def __init__(self, host, port, noOfSensors=10, multicast=False):
        CoAP.__init__(self, (host, port), multicast)

        for num in range(noOfSensors):
            self.add_resource('humidity'+num+'/', HumidityResource(num))

此摘录是生成以下内容的程序的一部分:

Traceback (most recent call last):
  File "humidityserver.py", line 10, in <module>
    class HumidityServer(CoAP):
  File "humidityserver.py", line 14, in HumidityServer
    for num in range(noOfSensors):
NameError: name 'noOfSensors' is not defined

即使我已经为变量定义了默认值,为什么还会发生这种情况?

还没有实例化所以class时执行的默认值是Created man

您在代码中混用了制表符和空格;这是您粘贴到问题中的原始代码:

灰色实线是制表符,点是空格。

注意 for 循环是如何缩进到 8 个空格,而 def __init__ 是如何缩进一个制表符的? Python 将制表符扩展到 8 个 个空格,而不是四个,因此 Python 您的代码看起来像这样:

现在您可以看到 for 循环在 外部 __init__ 方法,noOfSensors 变量来自 __init__ 那里没有定义函数签名。

不要在缩进中混用制表符和空格,坚持 制表符或 空格。 PEP 8 Python 风格指南 strongly advises you to use only spaces for indentation。例如,您的编辑器可以很容易地配置为在您使用 TAB 键时插入空格。

我复制并 运行 代码,这不是因为 @Martijn 回答的混合制表符和空格问题。在基于 classes.

创建一个小游戏时,我 运行 遇到了类似的问题

即使我已经为变量分配了一个默认值,但它卡住了并给我错误:

NameError: name 'mental' is not defined #where mental is the variable

我研究了一下,看到有人在谈论实例。然后我尝试创建一个实例并让实例执行函数,同时我定义了一个函数来执行我想要执行的。它成功了。下面是我的修复示例:

class People(object):
    def __init__(self, vital, mental):
    self.vital = vital
    self.mental = mental

class Andy(People):
        print "My name is Andy... I am not the killer! Trust me..."
        chat1 = raw_input(">")
        if chat1 == ('i believe you' or 'yes i believe' or 'believe' or 'i trust you' or 'yes i trust you'):
            self.mental += -1
            print "(checking) option 1"
        elif chat1 == ('you are killer' or 'you are the one' or 'really?' or 'i doubt' or 'i don\'t believe' or 'i don\'t trust you'):
            self.mental += 1
            print "(checking) option 2"
        else:
            print "Pass to else"
            print self.mental
            print self.vital

andy = Andy(1, 5)

我找到的解决方案是:

class People(object):
    def __init__(self, vital, mental):
    self.vital = vital
    self.mental = mental

class Andy(People):
    def play(self):
        print "My name is Andy... I am not the killer! Trust me..."
        chat1 = raw_input(">")
        if chat1 == ('i believe you' or 'yes i believe' or 'believe' or 'i trust you' or 'yes i trust you'):
            self.mental += -1
            print "(checking) option 1"
        elif chat1 == ('you are killer' or 'you are the one' or 'really?' or 'i doubt' or 'i don\'t believe' or 'i don\'t trust you'):
            self.mental += 1
            print "(checking) option 2"
        else:
            print "Pass to else"
            print self.mental
            print self.vital

andy = Andy(1, 5)
andy.play()

也许您的问题还有其他解决方案,但我是编程新手,您的代码中有些地方我不明白。但是关于你得到的错误,我认为它是因为 'self' 必须是你通过 class 为它设置为 运行 的实例。概念有误请指正