在python中动态创建变量 [英] dynamically creating variables in python
问题描述
我有一个存储变量名称和值的文件,如下所示:
I have a file that stores variable names and values like below:
name,David
age,16
score,91.2
...
我想编写一个python脚本来读取文件,并自动在对象中创建变量,而无需我实际进行操作,例如:
I want to write a python script that reads the file and automatically creates variables in an object without me actually doing it, something like:
self.name='David'
self.age=16
self.score=91.2
有可能这样做吗?我这样做的原因是,可能会有文件包含非常不同类型的变量,这些变量我之前都不知道.
Is it possible to do that? The reason I do this is there might be files containing very different types of variables which I don't know beforehand.
推荐答案
我这样做的原因是可能存在包含非常不同的文件我事先不知道的变量类型.
The reason I do this is there might be files containing very different types of variables which I don't know beforehand.
如果这是主要原因,则应使用字典.没有更好的办法.看到标记的重复项.
If this is the primary reason, you should use a dictionary. There's no better way. See the marked duplicates.
虽然通常建议在字典中保留类似变量,但是如果变量描述了一个类实例,则直接分配它们没有什么害处.如果字典键是任意的,建议您将字典传递给该类.
While it's usually recommended to keep like variables in a dictionary, if the variables describe a class instance there is no harm in assigning them directly. If the dictionary keys are arbitrary, I recommend you pass the dictionary to the class instead.
根据@Delgan的评论,您可以从文本文件创建字典,然后在迭代字典项时使用 setattr
.以下是使用 csv
模块并将逻辑包装在函数中的解决方案.
As per @Delgan's comment, you can create a dictionary from your text file and then use setattr
while iterating dictionary items. Below is a solution which uses the csv
module and wraps the logic in a function.
import csv
def add_attributes(obj, fn):
# create dictionary from text file
with open(fn, 'r') as fin:
d = dict(csv.reader(fin))
# iterate dictionary and add attributes
for name, value in d.items():
setattr(obj, name, value)
return obj
class myClass():
def __init__(self):
pass
A = myClass()
add_attributes(A, 'file.csv')
print(A.age) # 16
这篇关于在python中动态创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!