有什么方法可以把所有的信息从对象中打印出来?

2024-09-30 06:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python对象。在分析数据集的过程中,我创建了几个对象,并基于objectID将其保存在字典中

class TrackableObject:
    def __init__(self, objectID, centroid, timestart, timeend):
    # store the object ID, then initialize a list of centroids
    # using the current centroid
        self.objectID = objectID
        self.centroids = [centroid]
        self.timestart = timestart
        self.timeend = timeend

    #initialize a boolean used to indicate if the object has
    # already been counted or not
        self.counted = False
    def __str__(self):
        return str(self.objectID, self.timestart, self.timeend)
import pprint 
dictionary[objectID] = object 
pprint.pprint(dictionary)

当我打印最终的词典时,我收到:

{0: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee54b70>,
 1: <pyimagesearch.trackableobject.TrackableObject object at 0x7f6458857668>,
 2: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee54c50>,
 3: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee54be0>,
 4: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee54c18>,
 5: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee70588>,
 6: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee70438>,
 7: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee70400>,
 8: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee70630>,
 9: <pyimagesearch.trackableobject.TrackableObject object at 0x7f63fee70518>}

但我想看看这个物体的信息

{1:1,18:01,21:01 2: 2, 15:34, 14:18 ... }你知道吗

有没有什么方法可以用对象中的信息而不是对象的信息来打印字典


Tags: the对象self信息字典objectatpprint
3条回答

打印字典时,对字典的每个元素调用reprrepr调用__repr__方法。所以只需将__repr__添加到类中:

class TrackableObject:
    # some methods here including __str__ ...
    __repr__ == __str__

创建__repr__方法。就像你做的__str__

__str__返回对象的非正式或可打印的字符串表示形式。直接打印对象时,print使用它。但是当它在dict列表中并且您打印容器时,使用的是由__repr__定义的官方表示

TL/DR:将__str__替换为__repr__

def __repr__(self):
    return str(self.objectID, self.timestart, self.timeend)

相关问题 更多 >

    热门问题