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

Python循环中创建类实例时列表引用导致所有对象属性被同步更新的问题求助

问题分析与解决方案

嘿,我一眼就看出问题出在哪了——这是Python中可变对象引用的经典坑!

问题本质

你遇到的核心问题是:列表是Python中的可变引用类型。当你把follower_bucle_list和following_bucle_list作为参数传给User构造函数时,所有创建的User实例的对应属性,其实都指向同一个列表对象。后续调用clear()清空列表时,会直接修改这个共享的列表对象,导致所有User实例的对应属性都同步变成空列表。

两种解决方案

方案1:移除循环末尾的clear()调用(更简洁)

你已经在每次循环开头重新初始化了follower_bucle_list = []和following_bucle_list = []——这会创建全新的列表对象,和上一次循环的列表没有任何关联。所以完全不需要在循环末尾调用clear(),直接去掉这两行即可:

list_of_objects = []
list_of_objects.append(person)
for i in range(len(person.follower_list)):
    profile = instaloader.Profile.from_username(L.context, follower_list_[i])
    follower_bucle_list = []
    following_bucle_list = []
    for followee in profile.get_followers():
        follower_bucle_list.append(followee.username)
    for followee in profile.get_followees():
        following_bucle_list.append(followee.username)
    list_of_objects.append(
        User(follower_list_[i], len(follower_bucle_list) + 1, len(following_bucle_list) + 1, posts2, follower_bucle_list, following_bucle_list, biography2, fullname2, web2))
    print("|| Informació descarregada de l'usuari " + follower_list_[i] + " " + str(i + 1) + "/" + str(
        len(person.follower_list)))
    # 移除下面两行clear()调用
    # follower_bucle_list.clear()
    # following_bucle_list.clear()

这样每次循环的列表都是独立的新对象,User实例的属性引用的是各自的列表,后续循环不会影响之前的实例。

方案2:传入列表的副本(更灵活)

如果你一定要保留clear()操作(比如有其他逻辑需要复用这两个列表),可以在创建User实例时,传入列表的副本,让每个实例拥有独立的列表:

list_of_objects.append(
    User(follower_list_[i], len(follower_bucle_list) + 1, len(following_bucle_list) + 1, posts2, 
         follower_bucle_list.copy(),  # 传入副本
         following_bucle_list.copy(), # 传入副本
         biography2, fullname2, web2))

你也可以用list(follower_bucle_list)来创建副本,效果和copy()完全一样。这样即使后续清空原列表,副本的内容也不会受到影响。

补充说明

记住:在Python中,可变对象(列表、字典、自定义类实例等)传递的是引用,不是值的副本。如果多个变量/属性指向同一个可变对象,修改这个对象的内容会同步影响所有引用它的地方。这是新手很容易踩的坑,以后遇到类似问题可以先检查是不是引用共享导致的~

内容的提问来源于stack exchange,提问作者Marc Vergès

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:39:05