Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign class variables empty string and list them in order of definition

I am looking for a way to initialize a bunch of variables such that I can also print an array of those variables in the order they were defined. I thought using an enum class might help with that… so I took this working code that I cobbled together…

from enum import Enum
class all_vars(Enum):
    var1='1'
    var2='2'
    var3='3'
    var4='4'

var_array=[]
for items in all_vars:
    var_array.append(items.name)

print(var_array) --outputs ['var1', 'var2', 'var3', 'var4']

And modified it to my use case–initialize with empty string instead

from enum import Enum
class all_vars(Enum):
    var1=''
    var2=''
    var3=''
    var4=''

var_array=[]
for items in all_vars:
    var_array.append(items.name)
    
print(var_array) --outputs ['var1']  --need all the variables here

How do I make it include all the variables in the array in the second case. If Enum isn’t the way to go about this, I’m open to other alternatives. I am new to programming so please let me know if I am not making any sense or if I should add any other details. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Accessing items in the Enum in this way will only give you the first instance of each unique value you stored. However, the Enum does know what those other values are and that it has them, they are stored in the _member_map_ of the Enum. So you can access them like so:

var_array=[]
for item in all_vars._member_map_:
    var_array.append(item)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading