모든 요소를 인쇄하는 데 사용하려는 컨테이너 클래스가 있습니다.python에서 __repr __()을 올바르게 사용하고 있습니까?
파일이나 콘솔로 인쇄하고 싶습니다.
아래에 요소 (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__
의도 한대로 작동하지만 스타일/사용법이 괜찮은지 여부에 대해 의견을 말하십시오.
레이몬드 Hettinger (@raymondh)이 주제에 트윗 다른 일 : "가능한 경우,'__repr__' 메쏘드는 객체가 어떻게 구성되었는지 보여 주어야합니다. 불변 식은 :'eval (repr (obj)) == obj'이어야합니다." –
prettyPrint() 함수는 어떻습니까? 나는 prettyPrint 대신 PatchContainer의 __str() __을 정의 할 수있었습니다. – eugene
@Eugene 예. 'patchcontainer.prettyprint (file)'를 호출하는 대신에'print >> patch patchcontainer' (또는'print (patchcontainer, file = file)'를 사용하면됩니다. 'from __future__ import print_function'). IO를 수행하는 코드에서 비즈니스 레벨 클래스를 분리하는 것은 거의 항상 좋은 생각입니다. – lvc