是否有任何方法打印词典,其中包含来自对象的所有信息



我在python中有一个对象。在分析数据集的过程中,我创建Sevral对象并根据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 ...}

是否有任何方法在对象中使用信息而不是有关对象的信息打印字典?

创建__repr__方法。就像您做了__str__

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

TL/DR:用__repr__替换__str__

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

打印字典时,在字典的每个元素上都调用 reprrepr调用__repr__方法。因此,只需将__repr__添加到类:

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