我有一个容器类,我想用它来打印其中的所有元素。
我想将它们打印到文件或控制台。
我已经将元素 ( ) 和容器类布局Patch
如下,并且__repr__(self)
.
我不确定我是否理解它的目的,__repr__()
并且想知道这里的用法是否可以。
class Patch:
def __init__(self, folder_name, file_name):
self.folder_name = folder_name
self.file_name = file_name
self.full_path = os.path.join(self.folder_name, self.file_name)
self.file_hash = md5_for_file(open(self.full_path, 'r'))
self.file_size = os.path.getsize(self.full_path)
def __repr__(self):
return "%s %s %s" % (self.file_name, self.file_hash, self.file_size)
class PatchContainer:
def __init__(self):
self.patch_folder_dict = collections.OrderedDict()
self.patch_file_set = set()
def addPatch(self, patch):
if patch.file_name in self.patch_file_set:
print '*** Delete the file ', patch.full_path, ' ***'
return
self.patch_file_set.add(patch.file_name)
if not patch.folder_name in self.patch_folder_dict:
self.patch_folder_dict[patch.folder_name] = [patch]
else:
self.patch_folder_dict[patch.folder_name].append(patch)
def prettyPrint(self, writeable_object=PATCH_META_FILE):
sys.stdout = writeable_object
for patch_folder in self.patch_folder_dict.keys():
print patch_folder
patch_list = self.patch_folder_dict[patch_folder]
for patch in patch_list:
print patch
sys.stdout = sys.__stdout__
它按预期工作,但请评论样式/用法是否正常。