python - 将值存储到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']
解决方案
原始问题:
该__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())
推荐阅读
- ios - 非可选字符串自动更改为可选
- mysql - 如何创建文章表、分类和标签?
- r - 如何使用 dplyr 删除所有列中具有 NA 的行?
- java - 在 Jboss Wildfly 上部署 EAR 文件失败
- json - 你如何解析这个 JSON 数据?
- c# - 在 Asp.Net Core 和 Razor 视图中显示来自路径的图像?
- android - 转换列表
在颤动中进入json - c - 我的 C 代码没有在 Visual Studio 2017 上编译,并且一直给我一个错误,说它找不到特定的文件?
- r - read undirected graph csv file in R with library statnet
- php - 如何从php中的文件名中删除意外的点