📜  如何将字典更改为类?

📅  最后修改于: 2022-05-13 01:54:34.003000             🧑  作者: Mango

如何将字典更改为类?

使用 Dictionary 是一件好事,但是当我们得到很多字典时,它就会变得难以使用。因此,让我们了解如何将字典转换为类。

方法

让我们以一个简单的字典“my_dict”为例,它有 Name、Rank 和 Subject 作为我的键,它们的对应值是 Geeks, 1223, Python。我们在这里调用一个函数Dict2Class ,它将我们的字典作为输入并将其转换为类。然后我们使用循环遍历我们的字典 setattr() 函数将每个键作为属性添加到类中。

setattr() 用于为对象属性分配其值。除了通过构造函数和对象函数为类变量赋值的方法外,此方法还为您提供了另一种赋值方法。

下面是实现。

Python3
# Turns a dictionary into a class
class Dict2Class(object):
      
    def __init__(self, my_dict):
          
        for key in my_dict:
            setattr(self, key, my_dict[key])
  
# Driver Code
if __name__ == "__main__":
      
    # Creating the dictionary
    my_dict = {"Name": "Geeks",
               "Rank": "1223",
               "Subject": "Python"}
      
    result = Dict2Class(my_dict)
      
    # printing the result
    print("After Converting Dictionary to Class : ")
    print(result.Name, result.Rank, result.Subject)
    print(type(result))


输出:

After Converting Dictionary to Class : 
Geeks 1223 Python