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