首页 > 解决方案 > 类名未定义,但它是

问题描述

我只想创建一个class带有名称的静态字段的定义。一个名为的文件exercises.py包含:

第一个错误:

FAIL: test_00_packages (__main__.Ex00)
Traceback (most recent call last):
File "ex00.py", line 55, in test_00_packages
self.assertTrue("Exercise00" in globals()) 
AssertionError: False is not true

之后:

class Exercise00:
    def __init__(self, STUDENT_NAME):
        self.STUDENT_NAME = 'Name Name'

但是,如果我尝试打印Exercise00.STUDENT_NAME,我就会得到 NameError: name 'Exercise00' is not defined

但我想我定义了它?!

这里是完整的错误:

ERROR: test_01_static_field (__main__.Ex00)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "ex00.py", line 60, in test_01_static_field
    print("[I] Name: " + Exercise00.STUDENT_NAME)
NameError: name 'Exercise00' is not defined

----------------------------------------------------------------------

我的任务是创建一个带有静态字段的class调用。Exercise00STUDENT_NAME

ex00.py 中的行是:

def test_00_packages(self):
    self.assertTrue("Exercise00" in globals())

标签: pythonpython-3.x

解决方案


我想您需要定义STUDENT_NAME为类级别的字段,而不是实例级别的属性:

    class Exercise00:
        STUDENT_NAME = 'Name Name'

您可以在错误消息中注意到测试调用类级别字段Exercise00.STUDENT_NAME

print("[I] Name: " + Exercise00.STUDENT_NAME)

您还需要class Exercise00在测试模块中导入:

from exercises import Exercise00

只要将 import 语句与 test 一起添加到文件中ex00.py,类名字符串就会出现在globals()其中并且测试通过。


推荐阅读