在Python中的多个属性中转换dict属性
我有一个具有dict属性的类,如下所示:
I have a class with a dict attribute, like this :
class MyClass:
def __init__(self):
self.mydict = {'var1': 'value1', 'var2': 'value2', ...}
当我想获取值时,我必须这样做:
When I want to get the values, I have to do this :
cls = MyClass()
print(cls.mydict['var1'])
print(cls.mydict['var2'])
直接在属性中获取值的解决方案是什么?
What is the solution to get the values directly in attributes please :
cls = MyClass()
print(cls.var1)
print(cls.var2)
您可以向该类添加一个附加函数,该函数将能够解析字典并插入相关属性:
You could add an additional function to the class that will be able to parse the dict and insert the relevant attributes:
def assign_variables( self ):
for key, val in self.mydict.items():
setattr( self, key, val )
我正在使用内置的 setattr()
函数在此处设置具有动态名称/值的属性:
I'm using the built-in setattr()
function here to set attributes with dynamic names/values:
这是
getattr()
的对应项.参数是一个对象,一个字符串和一个任意值.该字符串可以命名现有属性或新属性.该函数将值分配给属性,前提是对象允许该属性.
例如,setattr(x, 'foobar', 123)
等同于x.foobar = 123
.
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
变量后在构造函数中调用此函数,甚至可以将循环放入构造函数中.
You can call this function inside your constructor after the mydict
variable is defined or even just place the loop in the constructor.