gpt4 book ai didi

python - 简单的Python类继承问题

转载 作者:行者123 更新时间:2023-11-28 22:02:02 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why do attribute references act like this with Python inheritance?
Python: derived classes access dictionary of base class in the same memory location

让我们看一下代码:

class parent:
book = {'one':1, 'two':2}

class child(parent):
pass

first = child()
second = child()

print first.book
print second.book

second.book['one'] = 3

print first.book
print second.book

当您“首先”运行此对象时,它的字典已被编辑!什么鬼?我认为“第一”和“第二”是“子”类的不同实例。这里发生了什么?为什么你在第二个编辑的内容会首先影响?

我可以通过在每个子类中重新创建书籍来“解决”这个问题,但这不是正确的方法,我想按照它们应有的方式使用类。

我做错了什么?

顺便说一句,我的主要语言是 cpp,所以我可能将 cpp 与 python 或类似的愚蠢的东西混淆了......

如有任何帮助,我们将不胜感激!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com