Python:Object有一个列表作为属性,但只存储引用而不是列表

时间:2014-04-01 18:20:17

标签: python list object attributes

我在Python 2.4(系统附带)中工作。 我尝试编译一个对象列表。每个Object都有一个属性,该属性是其他对象的列表。无论我做什么,在我看来,属性(列表)只存储引用而不是列表本身。 ControlPoint.LeafPairList是对LeafList的引用,但不包含列表本身。

稍后在脚本中我尝试用ControlPoint.LeafPairList [i]来解决LeafPair 这给了我相同的设置

有什么建议可以让它发挥作用吗?提前谢谢。

示例:

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"
...
}
}
}

1 个答案:

答案 0 :(得分:1)

好的,因为在Python中都是引用。我将用一个简单的例子来解释:

>>> l = [0, 0, 0]
>>> a = l
>>> a[0] = "Changed"

>>> print (l)
["Changed", 0, 0]
>>> print (a)
["Changed", 0, 0]

发生这种情况是因为声明a=l我们刚给对象添加了另一个名字[0, 0, 0]

要实现您的目标,您可以使用copy模块

>>> 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]