我在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 ... }
有什么方法可以打印带有对象信息而不是对象信息的字典?
答案 0 :(得分:0)
创建__repr__
方法。就像您做过__str__
。
答案 1 :(得分:0)
__str__
返回对象的非正式或可打印的字符串表示形式。当您直接打印对象时,print
使用它。但是,当它在字典列表中并且您要打印容器时,使用的是由__repr__
定义的正式表示形式。
TL / DR:将__str__
替换为__repr__
:
def __repr__(self):
return str(self.objectID, self.timestart, self.timeend)
答案 2 :(得分:0)
打印字典时,将在字典的每个元素上调用results = Article.objects.filter(Q(title__icontains=query) | movie_name__icontains=query)).distinct()
。
repr
调用repr
方法。因此,只需将__repr__
添加到课程:
__repr__