Python:对象具有一个列表作为属性,但仅存储引用而不存储列表 [英] Python: Object has a list as attribute but stores only a reference and not the list
问题描述
我使用Python 2.4(系统附带)进行工作.我尝试编译对象列表.每个对象都有一个属性,该属性是其他对象的列表.无论我做什么,在我看来,属性(列表)仅存储引用,而不存储列表本身. ControlPoint.LeafPairList
是对 LeafList
的引用,但不包含列表本身.
I work in Python 2.4 (comes with the system).
I try to compile a list of objects. Each Object has an attribute that is a list of other objects. Whatever I do it seems to me that the attribute(list) stores only a reference and not the list itself. ControlPoint.LeafPairList
is a reference to LeafList
but does not contain the List itself.
稍后在脚本中,我尝试使用ControlPoint.LeafPairList [i]处理LeafPair.总是给我相同的设置
Later in the script I try to address the LeafPair with ControlPoint.LeafPairList[i] that gives me always the same settings
有什么建议可以使其正常工作吗?预先感谢.
Any suggestions to make it work? Thanks in advance.
示例:
def ReadControlPoint(fh,ControlPoint):
line = fh.readline()
while not line.startswith('}'):
Scratch = line.split(' = ' )
if Scratch[0] == 'LeafPairList':
ReadLeafPairList(fh, LeafList)
setattr(ControlPoint, 'LeafPairList', LeafList)
else:
setattr(ControlPoint, Scratch[0], Scratch[1].strip('\n"'))
line = fh.readline()
def ReadLeafPairList(fh, LeafList):
del LeafList[:]
line = fh.readline()
while not line.startswith('}'):
Scratch = line.split(' = ')
Scratch = Scratch[1].strip('"\n').split()
Leafs = LeafPair(Scratch)
LeafList.append(Leafs)
line = fh.readline()
列表看起来像这样:
Machine = "Infinity_1"
Gantry = " 310.0"
Collimator = " 0.0"
Couch = " 0.0"
Weight = " 29.46 %"
NumberOfControlPoints = " 7"
NumberOfLeafPairs = " 80"
LeavesCanOverlap = " 1"
X2_Value = " 4.5"
X1_Value = " 4.5"
Y1_Value = " 9.0"
Y2_Value = " 9.0"
ControlPointList = {
ControlPoint = {
ControlPoint = " 0"
Weight = " 0.3"
LeftJawPosition = " 4.5"
RightJawPosition = " 4.5"
TopJawPosition = " 9.0"
BottomJawPosition = " 9.0"
LeafPairList = {
LeafPair(0) = " 0.5 0.0 0.5 -19.8"
LeafPair(0) = " 0.5 0.0 0.5 -19.2"
LeafPair(0) = " 0.5 0.0 0.5 -18.8"
LeafPair(0) = " 0.5 0.0 0.5 -18.2"
LeafPair(0) = " 0.5 0.0 0.5 -17.8"
}
}
ControlPoint = {
ControlPoint = " 1"
Weight = " 0.3"
LeftJawPosition = " 4.5"
RightJawPosition = " 4.5"
TopJawPosition = " 9.0"
BottomJawPosition = " 9.0"
LeafPairList = {
LeafPair(1) = " 0.5 0.0 0.5 -19.8"
LeafPair(1) = " 0.5 0.0 0.5 -19.2"
...
}
}
}
推荐答案
好吧,因为在Python中都是引用.我将通过一个简单的示例进行解释:
Ok thats because in Python all are references. I'll explain with a simple example:
>>> l = [0, 0, 0]
>>> a = l
>>> a[0] = "Changed"
>>> print (l)
["Changed", 0, 0]
>>> print (a)
["Changed", 0, 0]
之所以发生这种情况,是因为我们使用语句 a = l
将对象的另一个名称 [0,0,0]
This happend because with the statement a=l
we have just put another name to the object [0, 0, 0]
要获得所需的内容,可以使用 copy
模块
To achive what you want you can use copy
module
>>> import copy
>>> l = [0, 0, 0]
>>> a = copy.copy(l) # This is the only change.
>>> a[0] = "Changed"
>>> print (l)
[0, 0, 0]
>>> print (a)
["Changed", 0, 0]
这篇关于Python:对象具有一个列表作为属性,但仅存储引用而不存储列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!