首页 > 解决方案 > Python从字典创建类实例

问题描述

我有很多字段可以在我的程序运行时更改的类,但是当我在我的初始化中创建新对象时,我只能更改其中的一些,我想将这些更改保存到 JSON 文件,然后能够创建带有这些变量的新对象。除了让我的init接受 100 个参数之外,还有其他方法吗?

换句话说,我希望它是这样的:

class MyClass:
    def __init__(self, q, w):
        self.q = q
        self.w = w
        self.e = 30
        self.r = 40
        
a = MyClass(10,20)
dct = {'q': 100, 'w': 200, 'e': 300, 'r': 400}
print('before:', tmp.q, tmp.w, tmp.e, tmp.r)
for i in dct:
    #do sth here
print('after:', tmp.q, tmp.w, tmp.e, tmp.r)
before: 10 20 30 40
after: 100 200 300 400

标签: pythonjsonclassdictionary

解决方案


以下是使用关键字参数执行此操作的方法:

class MyClass:
    def __init__(self, **q):
        self.__dict__.update(q)

a = MyClass(a=10, b=20, c=50, d=69)

print(a.a)
print(a.b)
print(a.c)
print(a.d)

输出:

10
20
50
69


用字典:

class MyClass:
    def __init__(self, **q):
        self.__dict__.update(q)
        
dct = {'q': 100, 'w': 200, 'e': 300, 'r': 400}

a = MyClass(**dct)

print(a.q, a.w, a.e, a.r)

输出:

100 200 300 400

推荐阅读