Search code examples
pythoninitself

Storing values to init but it keeps overwriting the list when a new file read


I have two files and load into the class. File one is loaded and then create a string, then file two will load and create a string again and lastly both in one list. However, when I call the function, it just keep overwriting by the new file. Example, When file 2 is read then it only create strings for file 2 and overwrite file 1.

    class something():
    def getting(self, y):# string input "0" and "1"
        self.y = y #I have two files. y is a file. So if I have 2 files, then it will store 2 times into the self.y. Example, file one have "0" and "1" string
        self.fun1()

    def fun1(self):
        self.xx = []
        for i in range(2):
            self.xx.append("{} and {}".format(self.y, i)) #After getting the self.y, then it will append it into self.xx.
            # Example, 0 and 0 then 0 and 1; for y in "0" string.
            # Next, 1 and 0 then 1 and 1; for y in "1" string
            self.take()

    def take(self):
        return self.xx



a = ["0", "1"]
aaa = something()
for x in a:

    aaa.getting(x)

print(aaa.take())

Current output:

['1 and 0', '1 and 1']

Expected for the a.take:

['0 and 0', '0 and 1', '1 and 0', '1 and 1']

Solution

  • Based on an older post:

    I think you are overloading the variable 'a' in the following piece of code. By the time you are done with first iteration of the for loop, a has been changed with the code inside the loop. You must instead use another variable to track your list (something()).

    a = ["0", "1"]
    for x in a:
        a = something()
        a.getting(x)
    
        print(a.take)
    

    Try this:

    a = ["0", "1"]
    b = something()
    for x in a:  
        b.getting(x)
        print(b.take)
    

    Answer for the updated post:

    You are resetting self.xx in fun1(). What you must do is set self.xx to [] in the init function of something(). And, don't set self.xx to [] at start of fun1()