如何通过带有for循环的字典(python)设置实例的属性

问题描述 投票:0回答:1

我正在尝试通过字典将属性添加到此类。我有一本遵循该顺序的字典(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' object is not iterable

谢谢您的好人,如果您已阅读整本圣经:)

python class dictionary iterable
1个回答
0
投票

我认为您需要将dict.items更改为dict.items()

© www.soinside.com 2019 - 2024. All rights reserved.