在Python中的多个属性中转换dict属性 [英] Convert dict attributes in multiple attributes in Python

查看:110
本文介绍了在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 to x.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.

这篇关于在Python中的多个属性中转换dict属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆