我有一個容器類,我想用它來打印它中的所有元素。正確使用__repr __()在python中?
我想將它們打印到文件或控制檯。
我已經列出了元素(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__
它按預期工作,但請評論風格/用法是否正常。
雷蒙德赫廷傑(@raymondh)在推特上的主題有一天:「如果可能,'__repr__'方法應該顯示一個對象是如何構造的。不變式應該是:'eval(repr(obj))== obj'」。 –
prettyPrint()函數怎麼樣?我可以定義PatchContainer的__str()__而不是prettyPrint。 – eugene
@Eugene是的。這樣做可能會更有意義,所以,如果你這樣做,而不是調用'patchcontainer.prettyprint(file)',你將會執行'print >>文件patchcontainer'(或'print(patchcontainer,file = file)' 'from __future__ import print_function')。將業務級別與執行IO的代碼分開幾乎總是一個好主意。 – lvc