如何从字典创建一个类变量

huangapple go评论64阅读模式
英文:

How to create a class variable from dictionary

问题

我有一个Python字典我想要在类内部创建一个Python对象如下所示

my_dict = {'key1': 'value1', 'key2': 'value2'}

class A:
    key1 = value1
    key2 = value2

我尝试过的方法
1. 使用globals方法该方法创建全局变量但不能在类级别上访问它们因此无法使用A.key1访问它们
```python
globals().update(my_dict)
  1. 尝试使用类继承,但这会创建一个额外的变量来访问类中的变量。
class A:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
class B(A):
    a = A(**my_dict)
    start_date = 202219
    time = 0
    back_fall = {}

如果我想访问key1,我需要使用以下方式:B.a.key1


<details>
<summary>英文:</summary>

I have a python dict from which I want to create a python object inside a class like the following.

my_dict = {'key1': 'value1', 'key2': 'value2'}

class A:
key1 = value1
key2 = value2


Approaches I have tried
1. Using globals method, this method creates a global variables but not on class level this accessing them `A.key1`

globals().update(my_dict)

2. Tried using class inheritance but this creates an additional variable to access the variable in the class

class A:
def init(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class B(A):
a = A(**my_dict)
start_date = 202219
time = 0
back_fall = {}

If I want to access the `key1` I&#39;m doing the following `B.a.key1`



</details>


# 答案1
**得分**: 1

Python有一个内置方法称为 `setattr()`,可用于动态创建类变量。实现上述代码的示例代码如下。

```python
for key, value in my_dict.items():
    setattr(A, key, value)
英文:

Python has an inbuilt method called setattr() which can be used for dynamic class variable creation. Sample code to implement the above code is as following.

for key, value in my_dict.items():
    setattr(A, key, value)

答案2

得分: 0

使用self.__dict__在类内创建属性。

这是一个示例:

class A:
    def __init__(self, var_name, var_value):
        self.__dict__[var_name] = var_value

使用这个示例,您可以将您的字典传递给您的构造函数,然后您的构造函数应该循环遍历字典的键和值,并将它们相应地附加到self.__dict__中。

英文:

use self.__dict__ to create attributes inside a class.

here is an example

class A:
 def __init__(self,var_name,var_value):
  self.__dict__[var_name]=var_value

using this example you can pass your dictionary into your constructor and your constructor should loop through dictionary keys and values and append them to self.__dict__ accordingly

huangapple
  • 本文由 发表于 2023年5月25日 11:27:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定