将值存储到init,但在读取新文件时

时间:2018-10-30 04:30:44

标签: python init self

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

预期的拍摄次数:

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

2 个答案:

答案 0 :(得分:0)

原始问题:

__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())

答案 1 :(得分:0)

基于旧帖子:

我认为您在以下代码段中重载了变量“ a”。在完成for循环的第一次迭代时,a已被循环内的代码更改。相反,您必须使用另一个变量来跟踪列表(something())。

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

    print(a.take)

尝试一下:

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

更新后的帖子的答案:

您正在fun1()中重置self.xx。您必须做的是在something()的init函数中将self.xx设置为[]。而且,不要在fun1()开始时将self.xx设置为[]