Python 递归构造函数,变量共享
尝试遍历一个目录和子目录时,我在下面的代码中遇到错误。 这里,我尝试递归调用构造函数Python 递归构造函数,变量共享,python,Python,尝试遍历一个目录和子目录时,我在下面的代码中遇到错误。 这里,我尝试递归调用构造函数 import os from os.path import isfile, join class CovPopulate: fileList = list() def __init__(self,path): self.path = path for f in os.listdir(self.path): if isfile(join(s
import os
from os.path import isfile, join
class CovPopulate:
fileList = list()
def __init__(self,path):
self.path = path
for f in os.listdir(self.path):
if isfile(join(self.path,f)):
if f.endswith(".txt"):
fileList.append(join(self.path,f))
else:
CovPopulate(f)
回溯:-
CovPopulate(r"C:\temp")
File "<pyshell#1>", line 1, in <module>
CovPopulate(r"C:\temp")
File "C:/fuzzingresults/CovPopulate.py", line 11, in __init__
fileList.append(join(self.path,f))
NameError: global name 'fileList' is not defined
(r“C:\temp”)
文件“”,第1行,在
(r“C:\temp”)
文件“C:/fuzzingresults/CovPopulate.py”,第11行,在初始化中__
追加(join(self.path,f))
NameError:未定义全局名称“文件列表”
但是,我已经定义了fileList=list()
这次我检查了同步错误:/
文件列表
在类的命名空间中定义。我建议通过self
访问它。此外,当f
不是文件或目录(符号链接、管道等)时,我遇到了问题,因此我添加了isdir
检查。最后,只有将绝对路径传递到CovPopulate
时,我才能使代码工作。我的\uuuu init\uuuu
函数如下所示:
def __init__(self,path):
self.path = path
for f in os.listdir(self.path):
if isfile(join(self.path,f)):
if f.endswith(".txt"):
self.fileList.append(join(self.path,f))
elif isdir(join(self.path,f)):
CovPopulate(join(self.path,f))
你为什么要这样做?我完全看不出有什么理由把它变成一个类。@DanielRoseman,我知道没有理由,但类有助于重用,我可以只做一个函数并完成它,但我更喜欢为代码创建单独的类,类有助于名称空间,因为导入可能会冲突。我的所有实用程序函数都在一个文件中的不同类中定义。这样做有什么不对吗?@Tichodroma,什么?递归构造函数?。。只是为了学习,这是行不通的。我尝试了你的代码并做到了这一点。此外,fileList已经在类本身内部定义。。为什么需要一个自我?你仍然会得到一个名称错误
?顺便说一下,读一下:是的,这篇文章很有意义,我明白了。我需要使用静态变量来工作。