python - 类名未定义,但它是
问题描述
我只想创建一个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
调用。Exercise00
STUDENT_NAME
ex00.py 中的行是:
def test_00_packages(self):
self.assertTrue("Exercise00" in globals())
解决方案
我想您需要定义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()
其中并且测试通过。
推荐阅读
- r - 如何在 5 个月的窗口中使用 rollapply?
- c++ - 如何使用拖放功能和点击信号功能 QT 创建标签
- c# - 是否有一个好的软件模式来处理我想要一个抽象出内部类脆弱生命周期的外部包装类的情况?
- javascript - 如何计算由于实时数据而在 JavaScript 中发生变化的变量的总和?
- r - 使用函数扩展但得到不同的答案
- typescript - 如何在 vue-class 中为 v-model 使用计算属性?
- android - Android如何每25毫秒运行一次线程?
- php - 如何使用 Wordpress functions.php 中的高级自定义字段使脚本入队和出队?
- julia - 从数字数组中获取一个数字
- c# - FakeXRMEasy:使用 AddFakeMessageExecutor 覆盖更新请求行为