Python NameError:未定义名称“属性”
我一直在尝试重新编写以下代码,但它不起作用,有人可以帮助修复此问题吗 原代码:Python NameError:未定义名称“属性”,python,Python,我一直在尝试重新编写以下代码,但它不起作用,有人可以帮助修复此问题吗 原代码: def __str__(self): string = "" for attributeNum, attribute in enumerate(self.attributes): if attributeNum == len(self.attributes) - 1: string += str(attribute) else:
def __str__(self):
string = ""
for attributeNum, attribute in enumerate(self.attributes):
if attributeNum == len(self.attributes) - 1:
string += str(attribute)
else:
string += str(attribute) + ','
return string
重新编写的代码:
def __str__(self):
string = ""
update_string = string+str(attribute)
result = [update_string if attributeNum == len(self.attributes) - 1 else update_string + ','
for attributeNum, attribute in enumerate(self.attributes)]
print(result)
return string
错误:
Traceback (most recent call last):
File "MyClassifier.py", line 218, in <module>
classifier.test()
File "MyClassifier.py", line 170, in test
current_entry = (testEntry.euclidean(trainEntry), str(trainEntry.diabetes), str(trainEntry)
File "MyClassifier.py", line 15, in __str__
update_string = string+str(attribute)
NameError: name 'attribute' is not defined
属性变量是在for循环中声明的,因此尚未定义它-因此,错误消息显示名称“attribute”未定义。可能的修复是可能的;这里有一个:
def __str__(self):
string = ""
update_string = string+str(attribute)
result = [update_string if attributeNum == len(self.attributes) - 1 else update_string + ','
for attributeNum, attribute in enumerate(self.attributes)]
print(result)
return string
当询问产生异常的代码时,始终在问题中包含完整的回溯。复制回溯并将其粘贴到问题中,然后将其格式化为代码选择它并键入ctrl-k。请不要发布Traxceback或代码或数据的图像。错误说明了一切,在第二种情况下没有定义属性变量,那么您需要self.attribute而不是attribute什么不起作用?为什么不在self.attributes中为attribute返回.joinattribute?