在python中deque作为类中的属性

2024-06-25 07:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

from collections import deque
class testClass:
  def __init__(self):
    self.a = deque()
    self.c = deque()
    self.a.append(1)
    self.c.append(2)

  def testFunc1(self):
    self.b = self.a
    self.a = self.c
    self.c = self.b
    print(self.b.pop())

  def testFunc2(self):
    self.b = self.a
    self.a = self.a.append(10)
    print(self.b.pop())

TestInstance = testClass()
TestInstance.testFunc1() #answer will be 1
TestInstance.testFunc2() #answer will be 10

我只是不明白为什么这两个答案是不同的。两个函数都首先将self.a赋值给self.b。从结果中,我们可以看到,如果我们看testFunc2,如果self.a改变,self.b就会改变。但是,如果我们看testFunc1,如果self.a改变,self.b不会改变。为什么会这样?谁能给我解释一下吗?你知道吗


Tags: answerfromselfdefbepopwillcollections
1条回答
网友
1楼 · 发布于 2024-06-25 07:14:17

问题是self.b = self.a。通过使用=运算符,您认为这会创建一个新对象;实际上它不会。它只会创建一个共享原始对象引用的新变量。当您通过附加另一个元素来更改self.a时,self.b也会更改,因为它们指向相同的东西。根据需要使用copy()或deepcopy()。对于这个例子,我认为copy()就足够了。你知道吗

self.b = self.a改成self.b = copy.copy(self.a),你会得到你想要的。请别忘了import copy。你知道吗

阅读copy in Python了解详细信息。你知道吗

相关问题 更多 >