我有一个名为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