运行下面的代码后,我预计folders[0]
有1 File
而folders[1]
有0 File
秒。为什么代码会将File
插入两个 Folder
?
代码:
class Folder(object):
# __init__
def __init__(self):
pass
list_of_files = []
class File(object):
# __init__
def __init__(self):
pass
def insert_into_folder(self, folder):
folder.list_of_files.append(self)
def main():
folders = []
folders.append(Folder())
folders.append(Folder())
f = File()
f.insert_into_folder(folders[0])
for folder in folders:
print("Folder {:d} has {:d} file(s)".format(folders.index(folder), len(folder.list_of_files)))
if __name__ == "__main__":
main()
输出:
Folder 0 has 1 file(s)
Folder 1 has 1 file(s)
Process finished with exit code 0
答案 0 :(得分:1)
list_of_files
是一个类变量而不是实例变量,这意味着所有Folder
都具有相同的list_of_files
。通过将其更改为实例变量进行修复。
答案 1 :(得分:1)
正如其中一条评论所说:所有文件夹之间共享一个list_of_files
。
因此,在您的情况下,您希望每个文件夹都有自己的列表,因此您需要执行以下操作:
class Folder(object):
# __init__
def __init__(self):
self.list_of_files = []
class File(object):
# __init__
def __init__(self):
pass
def insert_into_folder(self, folder):
folder.list_of_files.append(self)
def main():
folders = []
folders.append(Folder())
folders.append(Folder())
f = File()
f.insert_into_folder(folders[0])
for folder in folders:
print("Folder {:d} has {:d} file(s)".format(folders.index(folder), len(folder.list_of_files)))
if __name__ == "__main__":
main()
<强>输出强>
Folder 0 has 1 file(s)
Folder 1 has 0 file(s)
通过添加self.list_of_files = []
,您实际上是在每次我创建Folder
的实例时,都会向此实例添加list_of_files。
答案 2 :(得分:1)
帕特里克指出,你Folder
定义的方式,list_of_files
是一个类变量,这意味着它对于类是“全局的”而且只有一个它的副本,在所有类的实例之间共享。
如果您希望每个文件夹都有自己的文件列表,请按以下方式定义文件夹:
class Folder(object):
def __init__(self):
self.list_of_files = []
答案 3 :(得分:1)
您需要一个实例变量,而不是类变量。
class Folder(object):
# __init__
def __init__(self):
self.list_of_files = []