Reputation: 2771
I'm low on the Python learning curve and I think missing something basic regarding class instantiation. In my code below, I have a simple class that contains formats for files and directories I want to save in a list during a recursive search. Filenames are save separately from directory names in the class and I have two instances. In one, I'm looking for files and directories with the text "RFI" in them, and the other I'm looking for "CCO". After running, the print statement shows all of the matches in both instances, rather than the RFI matches in the RFI instance and the CCO matches in the CCO instance. It's like "fileMatches" and "dirMatches" are behaving as static variables (if I'm getting my terminology correctly), so appending to one instance's list appends to both?
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)
Below is the output from the last print statement which shows the same values for both instances:
------- 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']
Upvotes: 1
Views: 2298
Reputation: 1905
This is because title
, nameFormats
etc. are static. These objects shared between all instances of Docs. If you want to each instance has its own lists then create them in constructor:
class Docs :
def __init__ (self, inTitle, inFormats):
self.title = inTitle
self.nameFormats = inFormats
self.title = []
self.nameFormats = []
self.fileMatches = []
self.dirMatches = []
Upvotes: 1