0

I have a lot of variables to initialize with one of my classes, and would rather not type them all out. Is there any way to initialize variables that have the same name as a string?

Semi-Psuedo code:

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)

This is so that I can access them later in my code, but there are so many specific variables. So far I have been using a dictionary to store all of the values but I would rather have it so that I can retrieve the value straight from the object itself rather than from a dictionary in the object.

ben10mexican
  • 51
  • 1
  • 5
  • 1
    If the goal is just arbitrary attributes, you may not need your own class, and could just [use `types.SimpleNamespace`](https://docs.python.org/3/library/types.html#types.SimpleNamespace), e.g. `t = types.SimpleNamespace(**dict(zip(array1, array2)))` – ShadowRanger Mar 18 '21 at 00:40
  • you can define a```>>> __eq__ ```method for the class and set it to a class attribute that is unique to each instance. Does this sound like it could work? – Kaleba KB Keitshokile Mar 18 '21 at 01:09

1 Answers1

2

You are looking for setattr:

class test:
    def __init__(self, arr1, arr2):
        for i, x in enumerate(arr1):
            setattr(self, str(x), array2[i])
fsl
  • 3,250
  • 1
  • 10
  • 20