首页 > 解决方案 > 将值存储到init,但在读取新文件时它会不断覆盖列表

问题描述

我有两个文件并加载到类中。加载文件一然后创建一个字符串,然后文件二将加载并再次创建一个字符串,最后都在一个列表中。但是,当我调用该函数时,它只会被新文件覆盖。例如,当读取文件 2 时,它只会为文件 2 创建字符串并覆盖文件 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())

电流输出:

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

预期的 a.take:

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

标签: pythoninitself

解决方案


原始问题:

__init__方法仅在对象创建时调用。例如:

o = something()

将创建该类的一个实例something(并将其存储为o)并执行该__init__方法。

对象上的进一步方法(其他)调用,例如您的getting方法,o将不会重新执行该__init__方法。

一个可能的解决方案是将附加到列表的代码移动到您正在调用的方法中:

class something():
    def __init__(self): 
        self.xx = []

    def getting(self, y):
        for i in range(2):
            self.xx.append("{} and {}".format(y, i))

o = something()

o.getting("0")
o.getting("1")

print(o.xx)

这给出了您描述的输出,但是我不完全确定您要达到的目标。我还建议使用替代变量/方法/类名称,具有描述其功能的名称有助于人类可读性。

编辑 2: 您仍在覆盖许多变量,请尝试:

class something():
    def __init__(self):
        self.xx = []

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

    def take(self):
        return self.xx



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

print(aaa.take())

推荐阅读