【发布时间】:2012-08-26 04:41:10
【问题描述】:
可能重复:
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 或类似的东西混淆了......
任何帮助将不胜感激!
【问题讨论】:
-
查看我对重复问题的回答:我认为它解释了您要查找的内容。
-
谢谢大家!我阅读了回复,并相应地更改了我的代码。还在学习python...非常感谢!