名称错误:未定义名称“attribute”

2024-10-05 10:41:31 发布

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

我一直在尝试重新编写以下代码,但它不起作用,有人能帮我解决这个问题吗?在

原代码:

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

重写代码:

^{pr2}$

错误:

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

Tags: 代码inpytestselfstringlineattribute
1条回答
网友
1楼 · 发布于 2024-10-05 10:41:31

attribute变量是在for循环中声明的,因此尚未定义它-因此错误消息显示“name'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

相关问题 更多 >

    热门问题