首页 > 解决方案 > 如何打印对象内容而不是它们的内存位置?

问题描述

我有带有 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 |

标签: pythonclassobject

解决方案


__repr__方法添加到Video

    def __repr__(self):
        return f"{self.title}, {self.url}, {self.tags}"

(在这里猜测一下,因为您没有显示Video类定义。)


推荐阅读