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
为什么即使我为变量定义了默认值,也会发生这种情况?
答案 0 :(得分:2)
您正在混合代码中的制表符和空格;这是粘贴到问题中的原始代码:
灰色实线是标签,点是空格。
注意for
循环如何缩进到8个空格,但是def __init__
缩进一个标签? Python将标签扩展为八个空格,而不是四个,因此对于Python,您的代码将改为:
现在您可以看到for
循环在之外的__init__
方法,noOfSensors
函数签名中的__init__
变量是那里没有定义。
不要在缩进中混合制表符和空格,坚持只标签或只是空格。 PEP 8 Python风格指南strongly advises you to use only spaces for indentation。例如,只要您使用 TAB 键,就可以轻松地将编辑器配置为插入空格。
答案 1 :(得分:0)
我复制并运行了代码,这不是因为@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()
也许您的问题还有其他解决方案,但是我在编程中还是一个新手,您的代码中有些东西我听不懂。但是关于错误,我认为由于“自我”而产生的错误必须是您设置的实例才能在类中运行。如果我弄错了概念,请纠正我。
答案 2 :(得分:-3)
它不是实例但是当类是Created man
时执行的defalut值