python - 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
解决方案
以下是使用关键字参数执行此操作的方法:
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
推荐阅读
- php - Laravel 5.6 从自定义路径而不是默认视图路径呈现邮件
- c# - 如何在我自己的 ContentView(自定义控件)中使用 Xamarin.Forms.Setter 类?
- javascript - 带有函数的 Typescript 中的映射类型
- php - 如何解决php错误未定义变量:id?
- python-2.7 - 如何在 python 2 中解压缩元组以及为什么我的这段代码显示错误?
- nginx - 请求网址中的无穷大
- google-cloud-storage - 如何恢复云存储中已删除的文件?
- php - 数据未插入 sql 数据库
- python - tkinter - 设置图标
- react-native - react-native 链接和安装本机依赖项