开发者社区> 问答> 正文

python数组类变量内的数组数据被同时修改了,该怎么解决

class Student:
    name = ''
    score = []
    def __init__(self):
        pass

def main():
    all = []
    all.append(Student())
    all.append(Student())
    all[0].name = 'YYY'
    all[1].name = 'XXX'
    all[0].score.append(75)
    all[1].score.append(85)
    print(all[0].score, all[1].score)

if __name__ == "__main__":
    main()

为什么print出来的是([75, 85], [75, 85]),数据被同时修改了。 请问如何让变量指向不同的地址?即我希望得到([75],[85])

展开
收起
海边一只船 2020-05-27 15:36:12 743 0
1 条回答
写回答
取消 提交回答
  • 不要把score和name定义类属性,而是要定义为对象属性,即:

    class Student:
        def __init__(self):
            self.score=[]
            self.name=''
    
    
    

    就可以了

    2020-05-27 17:53:53
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载