python - NameError:名称未在 python init 函数中定义

标签 python init nameerror

<分区>

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

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

最佳答案

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

enter image description here

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

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

source code at 8 spaces per tab

现在您可以看到 for 循环在 __init__ 方法的之外,并且 noOfSensors 变量来自__init__ 函数签名未在此处定义。

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

关于python - NameError:名称未在 python init 函数中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36917318/

相关文章:

python - 如何使用python从文本文件中删除特定行

init - systemd 生成器在引导过程中的什么时候运行?

javascript - React Native 最小/准系统设置

python - 在构造函数中初始化的列表上的 NameError [Python3]

python - 为什么我收到 NameError : global name 'spacing' is not defined

Python 创建一个线程并在按下按键时启动它

python - Keras:加载多个模型并在不同线程中进行预测

python - Django 如何在特定时间向用户显示消息

python - 将 Linux 引导选项传递给 Init

python - 为什么我会收到这个 NameError?我没有正确使用它吗?