我有一个容器类,我想用它来打印其中的所有元素。
我想将它们打印到文件或控制台。
我已经列出了元素(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__
它按预期工作,但请评论样式/用法是否正常。
答案 0 :(得分:4)
这看起来像你可能想要__str__
。它们是相似的,但是__str__
会返回供人类消费的东西; __repr__
应该返回用于Python消费的东西 - 它应该是一个Python表达式,它将评估为一个相等的对象,或者是一个尖括号中的东西,如默认的<classname object at id>
。请参阅内置repr(object)
的{{3}},最终调用object.__repr__()
:
对于许多类型,此函数尝试返回一个字符串 传递给eval()时会产生一个具有相同值的对象, 否则表示是用尖括号括起来的字符串 它包含对象类型的名称 其他信息
答案 1 :(得分:2)