【Python】简单实现对象的to_string方法

背景

每次定义一个类都要重写__str__方法,重点是如果是一堆属性的话,要拼接一个类似javato_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=)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章