python 使用传递给 class 的字典分配属性名称及其值

python assign attribute names and his values with a dictionary passed to the class

将变量传递给 class 变量的正常方法如下:

class makeGUI():
    def __init__(self,a):
        self.a = a

init里面的变量和属性一样被调用是约定俗成的。 我本可以做到:

class makeGUI2():
    
    def __init__(self,a):
        self.b = a

现在假设我想向 init 方法传递一个字典,其中包含属性的名称和它们应该采用的值。我尝试了以下方法:

class makeGUI3(): 
    def __init__(self,**Kwargs):
        for key,value in Kwargs.items():
            print(key,value)
            print(f'self.{key}={value}')
            exec(f'self.{key}={value}')
C = makeGUI3({'c':1234,'d':4567,'e':4567})

只要值是 int 类型,这就有效。 C 具有三个属性 c、d、e 以及相应的值。

然而,当传递的值不是 int 类型时,这会失败:

C = makeGUI3({'c':(1,2),'d':'lalala','e':[4,5,6,7]}) # does not work.

最后一行的结果是:

c (1, 2)
self.c=(1, 2)
d lalala
self.d=lalala
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-c9ae5d10f250> in <module>
----> 1 C = makeGUI3({'c':(1,2),'d':'lalala','e':[4,5,6,7]})

<ipython-input-14-a67330a26e5d> in __init__(self, mydict)
      4             print(key,value)
      5             print(f'self.{key}={value}')
----> 6             exec(f'self.{key}={value}')

<string> in <module>

NameError: name 'lalala' is not defined

我希望 class 构造函数与传递的数据类型无关。

我知道不推荐使用 exec,但我找不到其他方法。此外,如果有适当的方法可以将任何对象传递给 class 构造函数。正如您可以根据 class 的名称猜到的那样,这个想法是能够传递元素以在 class.

中构造一个小部件集合

谢谢。

使用setattr.

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.

class makeGUI3(): 
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

一种你可以实现的比非常简单的 hacky 方法是:

class makeGUI3:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

在内部,对象变量存储在 __dict__ 这是一个字典中。因此它有 update 方法可用。