【发布时间】:2012-11-02 05:11:19
【问题描述】:
好的,所以,我不太确定如何用一个简洁的短语来表达这个问题,所以如果模组能想出更好的标题,请修复它。
假设你有一个模块“testModule.py”
# testModule.py
data = {'x': 1, 'y': 2, 'z': 3}
class A:
def __init__(self):
pass
class B(A):
def __init__(self):
self.classData = data
class C(B):
def __init__(self):
B.__init__(self)
self.classData = {'x': 2, 'y': 2, 'z': 3}
然后将 testModule 导入文件“test.py”
# test.py
import testModule
b = testModule.B()
c = testModule.C()
print test.data
print b.classData
print c.classData
当你运行 test.py 时,你会得到:
{'x': 1, 'y': 2, 'z': 3}
{'x': 1, 'y': 2, 'z': 3}
{'x': 2, 'y': 2, 'z': 3}
这是意料之中的,很好,而且花花公子......
但是,如果您要将 testModule 中的 C 类更改为:
class C(B):
def __init__(self):
B.__init__(self)
self.classData['x'] = 2
然后运行 test.py 你得到:
{'x': 2, 'y': 2, 'z': 3}
{'x': 2, 'y': 2, 'z': 3}
{'x': 2, 'y': 2, 'z': 3}
所以我想我的问题是:为什么当您通过引用字典中的单个元素来更改属于基本模块的字典时,它是否会更改后续类的所有字典的该元素(我希望这使得感觉)。当您重新定义字典时,它不会这样做。请帮忙,因为这个问题真的开始困扰我了。
很高兴知道这些 .py 文件的结构是这样的,因为我目前在一个项目中遇到了这个问题,而且我的类遵循相同的结构。 提前谢谢大家, 杰拉尔达摩
【问题讨论】:
-
原因是python对象引用技术。 stackoverflow.com/questions/12797749/…
-
在你的例子中,你在 C 中使用父类中的对象,而不是在 C 中定义它
标签: python class dictionary