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