1

I'm accessing a class from another Python file by importing it at the top of the file. The class looks something like this:

class Something(object):
    a_dictionary = {1: 2, 3: 4, 5: 6}

    def __init__(self):
        stuff....

My question is how would I be able to access a_dictionary from the other file. I can't seem to find how to access a dictionary not within a function in another file.

I'm a beginner in Python and I have looked everywhere to find this answer and I can't. I essentially need to be able to iterate through the above dictionary from the other file.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Teddy
  • 55
  • 1
  • 2
  • 4

3 Answers3

3

Something like this should work:

from your_module import Something
print (Something.a_dictionary) # prints {1: 2, ...}
Horia Coman
  • 8,681
  • 2
  • 23
  • 25
1

in this case, a_dictionary is a class variable, and therefore part of the object's __dict__. You would access this dictionary in another file like this:

from your_file import Something

new_object = Something()
print(new_object.a_dictionary)

Accessing a class variable is done the same way as accessing an instance variable. The only difference between a class variable and instance variable is that class variables are the same value across all instances of an object, whereas an instance variable is specific to a single instance.

sam-pyt
  • 1,027
  • 15
  • 26
0
import otherfile

print(otherfile.Something.a_dictionary[1])

Output

2
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
  • @MarcusLind I reverted your edit, because it changed the code in this answer significantly. If you want to do things in a different fashion, post an answer of your own. – tripleee Nov 27 '17 at 08:07
  • I thought he wanted to access to a dictionary in a class of another file... so I imported the file and printed the dictionary... wasn't that the goal of the questions? – PythonProgrammi Nov 27 '17 at 18:26
  • 1
    I guess the upvotes were awarded at a time when this answer contained incorrect code. – tripleee Nov 27 '17 at 18:30