类的多个成员已更新,而不是一个



我已经创建了类文件:

@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)

在放入File类的3个对象后,我有一个列表a=[File,File,File],并调用:

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

列表A中的所有文件都已更新,因此看起来像:

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)]]

,但我希望它像:

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: []

列表填写如下:

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)

问题出在哪里?

您需要在init方法中移动变量定义。在init之外定义变量意味着这些变量将在所有对象之间共享。对于__name__pos_in_list__statements变量也是如此

@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)

您需要在set_matches((方法中添加额外的检查。在这里,您需要验证添加到列表中的对象是否已经存在于列表中。

对于__matches,您也可以使用set而不是list,但您需要确定如何比较两个数据类对象

相关内容

最新更新