【发布时间】:2014-01-06 21:11:55
【问题描述】:
我在 Python 中遇到了一个奇怪的列表问题。如果是 C++,我会在内存分配错误的行中想到可能导致此问题的某些内容
我有一本对象字典。每个对象都有一个已初始化的列表。
创建字典并初始化对象后,我会尝试访问属于字典中某个项目的列表。出于某种奇怪的原因,我似乎无意中使用了相同的列表来创建字典中的第二个和第三个对象,导致其他对象也打印了相同的列表。
如果可能的话,有人可以帮我吗?
这是我的代码:
import random
class ClassOne ():
name = ""
arrayToPrint = []
def __init__(self):
print("initialized class object")
name = ""
arrayToPrint = []
class ClassTwo:
nameTwo =""
x= {}
#Initializing the dictionary
for i in range(3): #Creating a dictionary with 3 items in it
classOne= ClassOne()
classOne.name = str(i)
#wanted to create each of the lists with random lengths
numberOfarraysToAdd =random.randint(1,9)
print ("number of arrayToPrint for class %d = %d" % (i, numberOfarraysToAdd))
for j in range(numberOfarraysToAdd):
#Initializing the list within the dictionary
classTwo = ClassTwo()
classTwo.nameTwo = random.randint(1,20)
classOne.arrayToPrint.append(classTwo)
x[i] = classOne #Copying the object of classOne into the dictionary with key as i
classOne = None
#Getting the code to print the dictionary and list
for i in x: #traversing the dictionary
print ("class name = %s" % x[i].name)
print ("arrayToPrint = [")
for j in range(len(x[i].arrayToPrint)-1): #traversing the list within the dictionary item
print ("f(%d) = %s\t" % (j, x[i].arrayToPrint[j].nameTwo))
print ("]")
这是我得到的输出。如果您观察到 f(0) 到 f(21) 对于所有类都是相同的。这告诉我 Python 在字典中的所有项目中使用了相同的列表,还是我做错了什么?
initialized class object
number of arrayToPrint for class 0 = 9
initialized class object
number of arrayToPrint for class 1 = 7
initialized class object
number of arrayToPrint for class 2 = 7
class name = 0
arrayToPrint = [
f(0) = 17
f(1) = 14
f(2) = 10
f(3) = 4
f(4) = 19
f(5) = 9
f(6) = 9
f(7) = 13
f(8) = 11
f(9) = 14
f(10) = 19
f(11) = 7
f(12) = 6
f(13) = 13
f(14) = 1
f(15) = 16
f(16) = 1
f(17) = 4
f(18) = 6
f(19) = 15
f(20) = 6
f(21) = 4
]
class name = 1
arrayToPrint = [
f(0) = 17
f(1) = 14
f(2) = 10
f(3) = 4
f(4) = 19
f(5) = 9
f(6) = 9
f(7) = 13
f(8) = 11
f(9) = 14
f(10) = 19
f(11) = 7
f(12) = 6
f(13) = 13
f(14) = 1
f(15) = 16
f(16) = 1
f(17) = 4
f(18) = 6
f(19) = 15
f(20) = 6
f(21) = 4
]
class name = 2
arrayToPrint = [
f(0) = 17
f(1) = 14
f(2) = 10
f(3) = 4
f(4) = 19
f(5) = 9
f(6) = 9
f(7) = 13
f(8) = 11
f(9) = 14
f(10) = 19
f(11) = 7
f(12) = 6
f(13) = 13
f(14) = 1
f(15) = 16
f(16) = 1
f(17) = 4
f(18) = 6
f(19) = 15
f(20) = 6
f(21) = 4
]
提前感谢您的帮助
【问题讨论】:
-
请修正缩进
-
我只想指出,将变量放在
__init__函数之外时,这与C++ 中的静态变量相同。类的所有实例对于这些变量将具有相同的值
标签: python arrays list object dictionary