【问题标题】:Declaring Class attributes in python from dictionary [duplicate]从字典中在python中声明类属性[重复]
【发布时间】:2016-06-15 10:44:39
【问题描述】:

这是我在 Stackoverflow 上的第一个问题,如果格式不完全正确,请见谅。

问题:

是否可以根据字典为类分配属性? 我想扔掉字典的键并从那里获取属性的名称。我举个例子。

class Clase():
    def __init__(self, dictionary):
        for key in dictionary.keys():
            self.key = dictionary[key]

dictionary={'attribute1': 'Zara', 'attribute2': 7, 'attribute3': 'First'}
PP = Clase(dictionary)

诚挚的问候和感谢!!

aMg

【问题讨论】:

    标签: python dictionary self


    【解决方案1】:

    你可以这样做:

    class Clase():
        def __init__(self, dictionary):
            for key in dictionary.keys():
                setattr(self, key, dictionary[key])
    
    dictionary={'attribute1': 'Zara', 'attribute2': 7, 'attribute3': 'First'}
    PP = Clase(dictionary)
    
    print(PP.attribute1)
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 2014-02-06
      • 2020-09-12
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多