Home > Enterprise >  Multiple members of class are updated instead of one
Multiple members of class are updated instead of one

Time:11-04

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:

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?

CodePudding user response:

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)

CodePudding user response:

You need to add additional check inside set_matches() method. Here you need to validate, if object, you add in the list, is already present in list or not.

You can also use set instead of list for __matches, but you need to be sure, how to compare two data classes objects

  • Related