背景
每次定義一個類都要重寫__str__
方法,重點是如果是一堆屬性的話,要拼接一個類似java
的to_string
方法要累死個人,pycharm
好像還沒有說能一鍵生成的功能,所以我需要一個簡單的方法節省我的時間.(備註:此前你要了解下__str__
的調用原理,這裏略過)
No bb , show code
方法:可複用在任何類的對象打印上
def obj_to_string(cls, obj):
"""
簡單地實現類似對象打印的方法
:param cls: 對應的類(如果是繼承的類也沒有關係,比如A(object), cls參數傳object一樣適用,如果你不想這樣,可以修改第一個if)
:param obj: 對應類的實例
:return: 實例對象的to_string
"""
if not isinstance(obj, cls):
raise TypeError("obj_to_string func: 'the object is not an instance of the specify class.'")
to_string = str(cls.__name__) + "("
items = obj.__dict__
n = 0
for k in items:
if k.startswith("_"):
continue
to_string = to_string + str(k) + "=" + str(items[k]) + ","
n += 1
if n == 0:
to_string += str(cls.__name__).lower() + ": 'Instantiated objects have no property values'"
return to_string.rstrip(",") + ")"
使用
def __repr__(self):
return 'Info(id={})'.format(self.id)
def __str__(self):
return obj_to_string(Info, self)
# 對比下
# return "Info(" + \
# "id=" + str(self.card_id) + \
# ", query=" + str(self.query) + \
# ", is_appear=" + str(self.is_appear) + \
# ", style=" + str(self.style) + \
# ", html_id=" + str(self.html_id) + \
# ", link_id=" + str(self.link_id) + \
# ", pos=" + str(self.pos) + \
# ", is_bad=" + str(self.is_bad) + \
# ", bad_reason=" + str(self.bad_reason) + \
# ", to_link=" + str(self.to_link) + ")"
輸出: 完美
Info(id=111,query=你好,is_appear=True,style=0,html_id=,link_id=,pos=,is_bad=False,bad_reason=,to_link=)