【问题标题】:How to set attributes of an instance through a dictionary with a for loop (python)如何通过带有for循环的字典(python)设置实例的属性
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多