【发布时间】:2020-12-21 15:46:04
【问题描述】:
假设我有一个类似的python类:
class User:
name = None
id = None
dob = None
def __init__(self, id):
self.id = id
现在我正在做这样的事情:
userObj = User(id=12) # suppose I don't have values for name and dob yet
## some code here and this code gives me name and dob data in dictionary, suppose a function call
user = get_user_data() # this returns the dictionary like {'name': 'John', 'dob': '1992-07-12'}
现在,将数据分配给用户对象的方法是userObj.name = user['name'] 和userObj.dob = user['dob']。假设,用户有 100 个属性。我将不得不明确分配这些属性。 Python中有没有一种有效的方法可以用来将字典中的值分配给对象中的相应属性?就像,字典中的name 键被分配给对象中的name 属性。
【问题讨论】:
-
您只是想将字典键设置为类中已经存在的变量,还是尝试在类中创建变量?因为动态创建变量绝对是错误的做法。如果你只是想设置变量值,那我们可以讨论一下。
-
我正在为已经存在的类变量设置值。
标签: python python-object