我有一个带有 dict 属性的类,如下所示:
class MyClass:
def __init__(self):
self.mydict = {'var1': 'value1', 'var2': 'value2', ...}
当我想获取值时,我必须这样做:
cls = MyClass()
print(cls.mydict['var1'])
print(cls.mydict['var2'])
请问直接在属性中获取值的解决方案是什么:
cls = MyClass()
print(cls.var1)
print(cls.var2)
请您参考如下方法:
您可以向该类添加一个附加函数,该函数将能够解析字典并插入相关属性:
def assign_variables( self ):
for key, val in self.mydict.items():
setattr( self, key, val )
我正在使用内置的 setattr() function在这里设置具有动态名称/值的属性:
This is the counterpart of
getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.
For example,setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.
您可以在定义 mydict 变量后在构造函数中调用此函数,甚至可以将循环放在构造函数中。
