You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何引用其他文件类生成的TrackLike对象并获取其属性?

解决TrackLike实例属性访问的AttributeError问题

你遇到的AttributeError: type object 'TrackLike' has no attribute 'items'错误,核心原因是你直接对TrackLike类调用了items()方法——items()是字典专属方法,而TrackLike是类本身,根本没有这个属性。你要操作的是已经存在likes_long列表里的TrackLike实例对象,不是类本身。

修正后的代码示例

for request in liked_tracks:
  likes_long.append(request)
print(f"the long list: {likes_long}")
print(f"the first entry: {likes_long[0]}") # 打印第一个track
likes_short = [] # 用来存储permalink_url的列表
likes_medium = [] # 用来存储转成字典后的列表

# 遍历已收集的TrackLike实例,而非TrackLike类
for track in likes_long:
    # 直接访问实例的permalink_url属性
    likes_short.append(track.permalink_url)
    
    # 将实例转成字典(两种可选方式)
    # 方式1:使用__dict__属性(大部分Python类默认支持)
    track_dict = track.__dict__
    # 方式2:如果TrackLike类提供了官方转字典方法(比如to_dict()),优先用这个
    # track_dict = track.to_dict()
    
    likes_medium.append(track_dict)
    print(track_dict)

关键说明

  • 所有TrackLike实例都存在likes_long列表中,遍历这个列表就能逐个处理每个对象
  • 访问实例属性直接用实例.属性名的格式,比如track.permalink_url
  • 转字典时,如果类有官方提供的转换方法(比如很多API SDK会提供to_dict()),优先使用官方方法,比__dict__更可靠

内容的提问来源于stack exchange,提问作者ItsMenace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:18:20