在Python中弹出不同列表时,会减少类实例变量

在Python中弹出不同列表时,会减少类实例变量,python,list,oop,Python,List,Oop,我正在尝试使用freecodecamp的概率计算器,可以找到 在从列表中随机选择n个项目的类函数中,我通过self.contents访问列表的内容,这是我制作的任何装满球的帽子的实例变量。我的函数如下所示: def draw(self,num_balls_drawn): randomlist = [] templist = self.contents if num_balls_drawn <= len(templist): for x in range(num_ball

我正在尝试使用freecodecamp的概率计算器,可以找到

在从列表中随机选择n个项目的类函数中,我通过
self.contents
访问列表的内容,这是我制作的任何装满球的帽子的实例变量。我的函数如下所示:

def draw(self,num_balls_drawn):
  randomlist = []
  templist = self.contents
  if num_balls_drawn <= len(templist):
    for x in range(num_balls_drawn):
      popped = templist.pop(random.randint(0, len(templist)-1)) # random has been imported
      randomlist.append(popped)
    return randomlist 

  else:
    return self.contents #If you ask for more items than there are in list, just returns list
然后用
hat=hat(蓝色=4,红色=2,绿色=6)
创建一个实例,然后用
print(hat.contents)print(hat.draw(7))print(hat.contents)print(hat.draw(7))测试我的函数。

我希望得到一份
['blue','blue','blue','blue','red','red','green','green','green','green','green']
帽子目录的
['blue','blue','red','green','blue','green']
帽子画(7)

但是,在第二次尝试使用这些语句时,返回的却是
['blue'、'blue'、'green'、'green']
,并且
['blue','blue','green','green','green']

两者的长度都只有5

尽管设置了一个临时列表
templast
,但每次我从
templast
中弹出一个项目时,我的
self.contents
仍然会缩短


如果有人能为我的问题提供解决方案,我们将不胜感激。

您的代码的问题在于self.contents是按地址而不是按值传递的。您可以做的是将
templast=self.contents
更改为
templast=self.contents[:]
。新的绘图功能如下:

def draw(self,num_balls_drawn):
  randomlist = []
  templist = self.contents[:]
  if num_balls_drawn <= len(templist):
    for x in range(num_balls_drawn):
      popped = templist.pop(random.randint(0, len(templist)-1)) # random has been imported
      randomlist.append(popped)
    return randomlist 

  else:
    return self.contents #If you ask for more items than there are in list, just returns list
def draw(自绘制、球数绘制):
随机列表=[]
templist=self.contents[:]

如果画了多少个球,你能创建一个吗?提供您期望的结果,以及我们可以运行并获得错误结果的内容。我应该研究什么来了解您所更改的内容为何起作用?Thanks@FredB通过价值和参考,我认为在C或C++中学习比在Python学习更容易,这里有一个小的解释,可以帮助你更好地理解它。您应该知道的是,您应该小心地分配列表,始终尝试复制/深度复制列表,这取决于您希望代码的行为方式。要了解这些概念,请参考以下链接:
def draw(self,num_balls_drawn):
  randomlist = []
  templist = self.contents[:]
  if num_balls_drawn <= len(templist):
    for x in range(num_balls_drawn):
      popped = templist.pop(random.randint(0, len(templist)-1)) # random has been imported
      randomlist.append(popped)
    return randomlist 

  else:
    return self.contents #If you ask for more items than there are in list, just returns list