我在Python程序中遇到过一种行为,我已经能够压缩成一个较小的程序。我很确定我已经遇到它并解决了它和过去,但不记得是怎么回事。
考虑以下Python程序:
import random
class B:
def __init__(self):
self.attr=random.randrange(0,10)
class A:
def __init__(self):
self.b=B()
list=[]
print "First pass"
for i in range(0,10):
a=A()
print "Random number in b: ",a.b.attr
list.insert(0,a)
print "Second pass"
for l in list:
print "Random number in b: ",a.b.attr
它通常输出如下内容:
First pass
Random number in b: 9
Random number in b: 7
Random number in b: 1
Random number in b: 5
Random number in b: 9
Random number in b: 7
Random number in b: 0
Random number in b: 6
Random number in b: 2
Random number in b: 7
Second pass
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
Random number in b: 7
我们如何解决这个问题?我知道它与Python如何复制对象等有关,但有:
import copy
list.insert(0,copy.deepcopy(a))
不能像人们期望的那样解决它。
答案 0 :(得分:1)
也许不是
print "Second pass"
for l in list:
print "Random number in b: ",a.b.attr
使用
print "Second pass"
for l in list:
print "Random number in b: ", l.b.attr