Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有任何方法可以使用脚本中的字符串初始化Python中的变量?_Python_Python 3.x - Fatal编程技术网

是否有任何方法可以使用脚本中的字符串初始化Python中的变量?

是否有任何方法可以使用脚本中的字符串初始化Python中的变量?,python,python-3.x,Python,Python 3.x,我有很多变量要用我的一个类初始化,我不想把它们全部输入。有没有办法初始化与字符串同名的变量 半伪密码: array1 = ["a", "b", "c", "d", "f"] array2 = [1, 2, 3, 4, 5] class test: def __init__(self, arr1, arr2): for i, x in enumerate(arr1):

我有很多变量要用我的一个类初始化,我不想把它们全部输入。有没有办法初始化与字符串同名的变量

半伪密码:

array1 = ["a", "b", "c", "d", "f"]
array2 = [1, 2, 3, 4, 5]

class test:
    def __init__(self, arr1, arr2):
        for i, x in enumerate(arr1):
            init_var("self." + x) = array2[i]
            
                        
t = test(array1, array2)
print(t.a)
print(t.b)

这是为了我以后可以在代码中访问它们,但是有太多的特定变量。到目前为止,我一直在使用字典来存储所有值,但我更希望使用它,以便直接从对象本身而不是从对象中的字典中检索值。

您正在查找
setattr

class test:
    def __init__(self, arr1, arr2):
        for i, x in enumerate(arr1):
            setattr(self, str(x), array2[i])

您正在查找
setattr

class test:
    def __init__(self, arr1, arr2):
        for i, x in enumerate(arr1):
            setattr(self, str(x), array2[i])

如果目标只是任意属性,您可能不需要自己的类,只需要,例如,
t=types.SimpleNamespace(**dict(zip(array1,array2))
您可以为类定义一个
>>\uu eq\uu
方法,并将其设置为每个实例唯一的类属性。这听起来像是可行的吗?如果目标只是任意属性,您可能不需要自己的类,只需要,例如,
t=types.SimpleNamespace(**dict(zip(array1,array2))
您可以为类定义一个
>>\uuu eq\uuuu
方法,并将其设置为每个实例唯一的类属性。这听起来像是可行的吗?