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 ... }
是否有任何方法可以使用对象中的信息而不是有关对象的信息来打印字典?
解决方案
__str__
返回对象的非正式或可很好打印的字符串表示形式。print
当您直接打印对象时使用它。但是当它在一个 dict 列表中并且您打印容器时,使用的是由定义的官方表示__repr__
。
TL/DR:替换__str__
为__repr__
:
def __repr__(self):
return str(self.objectID, self.timestart, self.timeend)
推荐阅读
- javascript - 从 json 文件中的链接插入图片
- android - 无法在 Android Studio 上启动模拟器:EventQueue.isDispatchThread()=false,然后无法定位 adb
- viper-lang - 双重权限吸入导致意外验证
- java - JPA 获取请求显示存储在数据库中的日期前一天
- git - 从主分支拉出时无法在本地找到图像“acbuild:latest”
- scala - 什么时候在 Scala 中使用 SBT 和 Ivy 模糊地选择了具有相同定义和类路径的两个类?
- c# - .Net Framework Web API FormsAuthentication.SetAuthCookie 不工作
- java - 提交后非法尝试将集合与两个打开的会话相关联
- reactjs - 如何组合来自父组件和子组件的 makeStyle 类?
- linux - “松散”的进程间通信