我有一个名为 Video 的 python 类,它代表 YouTube 视频。给定 YouTube 视频的 ID,Video 返回一个表示该视频的对象。但是,当第一次创建 Video 对象时,不会查询 YouTube。仅当要求提供需要来自 YouTube 的信息的属性时才会查询 YouTube。以下是它的工作原理:
>>> from video import Video
>>> video = Video('B11msns6wPU')
# 'B11msns6wPU' is the ID of a video
>>> video
Video(youtube_id="B11msns6wPU")
### As of now, no call to YouTube's API has been made
### Next, I ask for the title attribute. The object queries YouTube's API to get
### this information. In doing so, the object is completely initialized
>>> video.title
u'Badly Drawn Boy - Disillusion (directed by Garth Jennings)'
>>> video.duration
u'275'
# no query was made to the API because the object has been already been initialized
我不确定这在技术上是否是“懒惰的评估”,但它的味道相似。在第一次调用属性之前,不会初始化视频对象。我想知道这种技术是否值得实施。显然,它使我的代码更加复杂。你怎么认为?