我的 Python 学习曲线很低,我认为缺少一些关于类实例化的基本知识。在下面的代码中,我有一个简单的类,其中包含我想在递归搜索期间保存在列表中的文件和目录的格式。文件名与类中的目录名分开保存,我有两个实例。一方面,我正在寻找其中包含文本“RFI”的文件和目录,而另一个我正在寻找“CCO”。运行后,打印语句显示两个实例中的所有匹配项,而不是 RFI 实例中的 RFI 匹配项和 CCO 实例中的 CCO 匹配项。就像“fileMatches”和“dirMatches”表现为静态变量(如果我的术语正确),所以附加到一个实例'
import fnmatch
import os
path = '.'
allDocs = []
class Docs :
title = []
nameFormats = []
fileMatches = []
dirMatches = []
def __init__ (self, inTitle, inFormats):
self.title = inTitle
self.nameFormats = inFormats
allDocs.append(Docs('RFI','RFI*[0-999]*'))
allDocs.append(Docs('CCO','CCO*[0-999]*'))
for root, dirnames, filenames in os.walk(path):
print ("Root: " + root)
for currDoc in allDocs :
for currDirname in fnmatch.filter(dirnames, currDoc.nameFormats):
currDoc.dirMatches.append(currDirname)
for currFilename in fnmatch.filter(filenames, currDoc.nameFormats):
currDoc.fileMatches.append(currFilename)
print ("------- Results ----------")
for currDoc in allDocs :
print (currDoc.title, currDoc.nameFormats, "directory matches: ", currDoc.dirMatches)
print (currDoc.title, currDoc.nameFormats, " file matches: ", currDoc.fileMatches)
下面是最后一个打印语句的输出,它显示了两个实例的相同值:
------- Results ----------
RFI RFI*[0-999]* directory matches: ['RFI#04 Blah']
RFI RFI*[0-999]* file matches: ['CCO#02 Blah.pdf', 'CCO#01 Blah.pdf', 'RFI #1.pdf', 'RFI #2.pdf', 'RFI #3.pdf']
CCO CCO*[0-999]* directory matches: ['RFI#04 Blah']
CCO CCO*[0-999]* file matches: ['CCO#02 Blah.pdf', 'CCO#01 Blah.pdf', 'RFI #1.pdf', 'RFI #2.pdf', 'RFI #3.pdf']