python - 如何打印对象内容而不是它们的内存位置?
问题描述
我有带有 VideoLibrary 类的 video_library.py 模块:
class VideoLibrary: """用于表示视频库的类。"""
def __init__(self):
"""The VideoLibrary class is initialized."""
self._videos = {}
with open(Path(__file__).parent / "videos.txt") as video_file:
reader = _csv_reader_with_strip(
csv.reader(video_file, delimiter="|"))
for video_info in reader:
title, url, tags = video_info
self._videos[url] = Video(
title,
url,
[tag.strip() for tag in tags.split(",")] if tags else [],
)
def get_all_videos(self):
"""Returns all available video information from the video library."""
return list(self._videos.values())
def get_video(self, video_id):
"""Returns the video object (title, url, tags) from the video library.
Args:
video_id: The video url.
Returns:
The Video object for the requested video_id. None if the video
does not exist.
"""
return self._videos.get(video_id, None)
我正在尝试从我的 video_library.py 模块打印来自 get_all_videos() 的对象,但它打印对象位置而不是列表://这是我的 video_player.py 模块
Class VideoPlayer:
def show_all_videos(self):
"""Returns all videos."""
all_vids = self._video_library.get_all_videos()
for i in all_vids:
print(i)
结果:
<video.Video object at 0x000001DCED0539D0>
<video.Video object at 0x000001DCED0538E0>
<video.Video object at 0x000001DCED2386A0>
<video.Video object at 0x000001DCED3A12E0>
<video.Video object at 0x000001DCED3A1CA0>
我想要的是:
Funny Dogs | funny_dogs_video_id | #dog , #animal
Amazing Cats | amazing_cats_video_id | #cat , #animal
Another Cat Video | another_cat_video_id | #cat , #animal
Life at Google | life_at_google_video_id | #google , #career
Video about nothing | nothing_video_id |
解决方案
将__repr__
方法添加到Video
:
def __repr__(self):
return f"{self.title}, {self.url}, {self.tags}"
(在这里猜测一下,因为您没有显示Video
类定义。)
推荐阅读
- postgresql - 使用 POSTGRESQL 的记录和数组
- redirect - 未经请求的 URL 重定向
- ios - SWIFT:如何通过单击保存按钮在现有子项上添加键值?
- r - 如何在 word 文本文件的表格中报告 REPEATED MEASURES ANOVA 输出?
- android - 反应本机 firebase 实时数据库参考返回 null
- memory - 如何访问另一个进程的页表?
- powerbi - PowerBI 中的转换数据选项
- javascript - 替代 shouldComponentUpdate 的方法
- arduino - Arduino:如果串行输入字符串匹配,则继续,否则继续询问用户输入
- vb.net - 将框架 3.5 升级到 4.61 后,Rdlc 报告缺少 ansi 字体“sutonnyMj”的几个字符