清单&的Python奇怪行为附加 [英] Python Strange Behavior with List & Append
问题描述
以下代码是我遇到的问题,正在寻找解释.代码的行为与我预期的不同.代码下面是我的预期输出和实际输出.最后要注意的一点是,我理解这段代码可能是奇怪的",至少可以说使用range(1)有点奇怪.这样做的原因是程序中的这种确切出现(范围是变量,但处于这些值)会导致问题..所以我制作了此简单的代码来复制它.
The following code is an issue I encountered and am looking for an explanation. The behavior of the code different than what I expected. Below the code will be my expected output, and the actual output. One last thing to note, is that I understand this code may be 'strange', and that using range(1) is a bit odd to say the least. The reason for this is that this exact occurrence in a program (the ranges were variables but at these values) caused problems.. so I made this simple code to replicate it.
userList = []
class User():
listA = []
listB = []
def setup(self):
for i in range(1):
self.listA.append('a')
self.listB.append('b')
for i in range(5):
user = User()
userList.append(user)
for i in range(len(userList)):
userList[i].setup()
for i in range(len(userList)):
print str(userList[i].listA)
print str(userList[i].listB)
预期产量
['a']
['b']
['a']
['b']
['a']
['b']
['a']
['b']
['a']
['b']
实际输出
['a','a','a','a','a']
['b','b','b','b','b']
['a','a','a','a','a']
['b','b','b','b','b']
['a','a','a','a','a']
['b','b','b','b','b']
['a','a','a','a','a']
['b','b','b','b','b']
['a','a','a','a','a']
['b','b','b','b','b']
讨论
我感谢您解释为什么会这样.我不确定内置的append()函数是否会以某种方式影响所有用户,或者每个用户是否以某种方式共享其字段.在Python 2.7.3上运行.
I appreciate any explanation as to why this is happening. I'm not sure if the built-in append() function is somehow affecting all Users, or if each User is somehow sharing their fields. Running on Python 2.7.3.
推荐答案
将此与您的代码进行比较
Compare this to your code
class User():
def setup(self):
self.listA = [] # instance variable
self.listB = [] # instance variable
for i in range(1):
self.listA.append('a')
self.listB.append('b')
请注意,没有必要在类级别声明"任何变量
Note that it's not necessary to "declare" any variables at the class level
这篇关于清单&的Python奇怪行为附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!