我有一個名爲HashedDir的模塊(實際上是一個.py文件)。我的課堂如何表現得像一個靜態課程?
當我導入該類的文件和instanciate 2實例時,當我檢查對象的字段時,它們始終是相同的,即使這兩個對象應該不同。
如:
h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
任何想法?
這是類:
from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
在此先感謝
你shoul d發佈該課程的代碼。 – Corey 2009-01-27 11:43:07
你的代碼沒有寫作的意義。你已經導入/重命名os.walk,os.path,md5.md5並沒有提到。一旦糾正,我們發現HashedDir的實例不具有* .value attirbute(從上面的代碼可以看出)。 – bendin 2009-01-27 12:18:11
>>> a = HashedDir(「/ home/smithma/tmp」);打印a.value中 回溯(最近通話最後一個): 文件「」,1號線,在 AttributeError的:HashedDir實例沒有屬性「值」 –
bendin
2009-01-27 12:18:58