Search code examples
pythonvariablesglobalself

self variables not being stored in python?


I'm declaring self variables in my program regularly:

def __init__(self):
    self.x = dict()

And later on in my code (the first function that is called), I assigned a value to self.x. However later on when I try to actually use self.x in later functions, self.x prints out as {}. Even though I know for sure that I am assigning it correctly and that my data is sound.

Bit of a python noob here, is there anything I may be missing? Should I declare these variables as global since maybe I am losing scope in the way my program is written?

Thanks


Solution

  • It's hard to answer your question without seeing the rest of your code (I will edit this post when you give more information), but maybe I can give you some insight into what might be the problem. Your functions should probably look something like those shown in the class below:

    class Foo:
        def __init__(self):
            self.x = dict()
    
        def add(self):
            self.x[1] = 'a'  # add something to our dict
    
        def redefine(self):
            self.x = {2:'b', 3:'c'}  # reassign our dict
    

    So to see that everything is in order:

    foo = Foo()
    print foo.x
    foo.add()
    print foo.x
    foo.redefine()
    print foo.x
    

    Output:

    {}
    {1: 'a'}
    {2: 'b', 3: 'c'}