r/learnpython•
Embogenous

Reference variables not in the scope of an object/module using a string?

Two questions, actually;

If I have the following code:

class C:
    def __init__(self):
        self.var = 0

c = C()

Then I can reference var using getattr(C,"var"). And if I have:

#file1.py

var = 0

#file2.py

import file1
getattr(file1,"var")

Is it possible for me to reference a variable defined within that module in a similar way?

i.e.

var = 0
getattr(thisfile,"var") #or an equivalent command

Second question is, can I define variables using this method? Say if I want to create 50 variables (and not use a list for whatever reason), instead of using;

var1,var2,var3... = 0,0,0...

Can I go:

for x in range(1,51):
    definevariable("var"+str(x))

Or similar?

Posted May 2, 2012, 9:32 PM UTC

16
Loading comments…