python - 如何在python中建模特殊类实例
问题描述
我想在 python 中创建一个类,其中包括类的特殊实例的类级常量。即是这样的:
class Testing:
SPECIAL = Testing("special")
def __init__(self, name):
self.name = name
def test_specials():
norm = Testing("norm")
assert norm.name == "norm"
assert Testing.SPECIAL.name == "special"
如果我尝试上面的代码,它会失败说:NameError: name 'Testing' is not defined
.
我应该如何建模?
解决方案
感谢安东尼的上述回答。解决方案是这样的:
class Testing:
def __init__(self, name):
self.name = name
Testing.SPECIAL = Testing("special")
def test_specials():
norm = Testing("norm")
assert norm.name == "norm"
assert Testing.SPECIAL.name == "special"
推荐阅读
- javascript - SQL 在浏览器中的 apache 箭头之上?
- charts - Chart.js 忽略选项
- prometheus - 如何在普罗米修斯 predict_linear 中使用预测
- javascript - 对 React 中的未定义错误感到困惑
- c# - 如何在 C# 中编写授权级别函数?
- java - 未捕获 lambda 抛出的 Java 未经检查的异常
- smtp - 将 DKIM 与 SMTP TELNET 连接一起使用
- javascript - 用于有条件地更改链接 URL 的 JavaScript 代码
- ffmpeg - 从 PNG 文件制作 Alpha Mask 视频
- react-native - 我需要使用 sdk 25 和 gradle 2 创建 react-native 应用程序