【发布时间】:2020-08-14 06:24:32
【问题描述】:
我正在尝试通过字典向此类添加属性。我有一本遵循这个顺序的字典(dict)
{'Subject' + str(number) : subject introduced previously}
例如,
{'Subject0' : 'Chemistry'}
所以我试图在一个类上实现它,如下所示:
class Subjects:
def __init__(self, name, dictVar, yearCourse):
self.name = name
self.dictVar = dictVar
self.yearCourse = yearCourse
self.label = self.name [0:3] + self.yearCourse
def getLabel(self):
print (self.label)
for key, value in dict.items:
key = Subjects(value, key, yearCourse)
原码有对应标识,是格式错误
我从question 中取出了 dict.items
如果我跑了
Subject0.getLabel()
什么也没发生,因为我显然在 for 循环中有错误
for key, value in dict.items:
TypeError: 'builtin_function_or_method' 对象不可迭代
如果你读过整本圣经,谢谢你好人:)
【问题讨论】:
-
您需要调用
dict.items,例如将您的for循环更改为for key, value in dict.items():
标签: python class dictionary iterable