名称错误:python init函数中未定义名称

2024-05-18 23:28:30 发布

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

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

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


Tags: inself程序hostforinitportrange
3条回答

它还没有实例化,所以当创建类时执行的defalut值为man

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

enter image description here

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

注意for循环如何缩进到8个空格,而def __init__如何缩进一个制表符?Python将制表符扩展为8个空格,而不是4个,因此对Python来说,代码如下所示:

source code at 8 spaces per tab

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

不要在缩进中混合制表符和空格,坚持使用只是制表符或只是空格。PEP 8 Python风格指南strongly advises you to use only spaces for indentation。例如,只要使用选项卡键,就可以轻松地将编辑器配置为插入空格。

我复制并运行了代码,这并不是因为@Martijn回答了标签和空格的混合问题。我在创建一个基于类的小游戏时遇到了类似的问题。

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

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”必须是一个你设置的实例,它才能在类中运行。如果我弄错了概念,请纠正我。

相关问题 更多 >

    热门问题