0

私はPythonを初めて使用し、以下に表示されている動作を説明するものを見つけることができませんでした。メソッドからリストを返すときに問題に気づき、問題を示す最も単純な形式にリストを絞り込みました。私は回避策を見つけましたが、両方の例が同じように動作することを期待しているので、理解に欠けているものを知りたいと思います。

class MyCount:
    """A simple count test to show return list problem"""
    def __init__(self):
        self.next = [0]

    def count_good(self):
        self.next[0] += 1
        return [self.next[0]]

    def count_bad(self):
        self.next[0] += 1
        return self.next # returning using this form corrupts the recieving list


c=MyCount()
result=4*[0]
result[0]=c.count_good()
result[1]=c.count_good()
result[2]=c.count_bad()
print result
result[3]=c.count_bad()
print result


>>> c=MyCount()
>>> result=4*[0]
>>> result[0]=c.count_good()
>>> result[1]=c.count_good()
>>> result[2]=c.count_bad()
>>> print result
[[1], [2], [3], 0]
>>> result[3]=c.count_bad()
>>> print result
[[1], [2], [4], [4]]   <--- the return changed the previous item in the list
>>>
>>> c=MyCount()
>>> result=4*[0]
>>> c.count_good()
[1]
>>> c.count_good()
[2]
>>> c.count_bad()
[3]
>>> c.count_bad()  <--- seems to work fine when not returning to a list
[4]
>>> 
4

1 に答える 1

4

の場合、コピーではなく、参照する実際のリスト オブジェクトreturn self.nextの参照を返しています。したがって、どこからでも元のリスト オブジェクトに加えられた変更は、その元のオブジェクトを参照するすべての場所に反映されます。self.next

コピーを返すには、完全なスライスを作成する必要があります。

return self.next[:]

または次のlist()関数を使用します。

return list(self.next)
于 2012-04-25T04:33:36.613 に答える