1

这是代码:

class Foo:
  def __init__(self):
    self.l = [1, 2, 3]

  def get_list(self):
    return self.l

f = Foo()
l2 = f.get_list()
print(f.get_list())
l2.remove(2)
print(l2)
print(f.get_list())

这是运行:

>python /tmp/1.py
[1, 2, 3]
[1, 3]
[1, 3]

所以函数 get_list() 返回引用。

有没有办法让它返回值?

4

2 回答 2

1

似乎是使用列表复制的好地方。

class Foo:
  def __init__(self):
    self.l = [1, 2, 3]

  def get_list(self):
    return self.l.copy()

或者

class Foo:
  def __init__(self):
    self.l = [1, 2, 3]

  def get_list(self):
    return self.l[:]

于 2019-09-14T04:21:36.917 回答
1

您可以像这样返回列表的副本

def get_list(self):
    # It will return shallow copy of the list.
    return self.l.copy()

或者,您也可以像这样使用 deepcopy 模块进行 deepcopy

from copy import deepcopy 

def get_list(self):
    return deepcopy(self.l)

例如。

a = [[1,2,3],[2,3]]
b = a.copy()

# If I append something to a, b will be unchanged.
a.append(1)
# a = [[1,2,3],[2,3], 1]
# b = [[1,2,3],[2,3]]

# If I modify any object inside a, it will also reflect in b. i.e. shallow copy.
a[0].append(5)
# a = [[1,2,3,5],[2,3], 1]
# b = [[1,2,3,5],[2,3]]

在 deepcopy 的情况下, b 仍然保持不变,即 deepcopy 也会复制内部对象。

于 2019-09-14T04:25:42.540 回答