英文:
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)
- 尝试使用类继承,但这会创建一个额外的变量来访问类中的变量。
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'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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论