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

Multiple members of class are updated instead of one

I have created class File:

@dataclass
class Match:
    length: int
    pos_A: int
    pos_B: int
    f_index: int

class File:
    __name = ""
    __pos_in_list = 0
    __statements = []
    __matches = []

    def __init__(self, name: str, pos: int, statements: [Statement]):
        self.__name = name
        self.__pos_in_list = pos
        self.__statements = statements
   
    def set_matches(self, matches: [Match]):
        self.__matches.append(matches)


After putting 3 objects of class File, so i have a list A = [File, File, File] and calling:

A[0].set_matches[Match(1,2,3,4)]

all files in list A are updated, so it looks like:

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

pos_in_list: 0 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 1 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 2 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]

,but I would like to have it like:

pos_in_list: 0 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 1 matches: []
pos_in_list: 2 matches: []

List is filled like:

    files = []
    for i in range(len(parsed_text)):
        statements = []
        for func in parsed_text[i]:
            statements.extend(parse_text_into_tokens(func + ";"))
        f = File(filenames[i], i, statements)
        files.append(f)

Where is the problem?

>Solution :

You need to move variable definition inside the init method. Defining variable outside of init means that those variables will be shared amongst all objects. Same goes for __name, __pos_in_list and __statements variables too

@dataclass
class Match:
    length: int
    pos_A: int
    pos_B: int
    f_index: int

class File:
    __name = ""
    __pos_in_list = 0
    __statements = []

    def __init__(self, name: str, pos: int, statements: [Statement]):
        self.__matches = []
        self.__name = name
        self.__pos_in_list = pos
        self.__statements = statements
   
    def set_matches(self, matches: [Match]):
        self.__matches.append(matches)
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