【问题标题】:Why are there immutable objects in Python? [duplicate]为什么 Python 中有不可变对象? [复制]
【发布时间】:2015-10-14 22:58:16
【问题描述】:

所以 Python 是通过引用传递的。总是。但是像整数、字符串和元组这样的对象,即使被传递到函数中,也不能改变(因此它们被称为不可变的)。这是一个例子。

def foo(i, l):
  i = 5 # this creates a new variable which is also called i
  l = [1, 2] # this changes the existing variable called l

i = 10
l = [1, 2, 3]
print(i)
# i = 10
print(l)
# l = [1, 2, 3]
foo(i, l)
print(i)
# i = 10 # variable i defined outside of function foo didn't change
print(l)
# l = [1, 2] # l is defined outside of function foo did change

所以你可以看到整数对象是不可变的,而列表对象是可变的。

在 Python 中甚至有不可变对象的原因是什么?如果所有对象都是可变的,那么像 Python 这样的语言会有哪些优点和缺点?

【问题讨论】:

  • 不可变对象更快。
  • 1这个号码你能改变什么?
  • @TigerhawkT3 我知道这是真的,但是即使一些常用的对象很慢,语言当然也有范式优势。
  • 您将不变性与范围界定混淆了。 foo 中的 i 变量与全局 i 变量不同。您可以在foo 中的i = 5 上方添加global i,但使用全局变量是不好的做法,因为它会使代码更难推理。
  • @bourbaki4481472 - 也许您应该实际测试过您发布的代码。

标签: python immutability


【解决方案1】:

您的示例不正确。 l 没有foo() 的范围之外更改。 foo() 内部的 il 是指向新对象的新名称。

Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(i, l):
...   i = 5 # this creates a local name i that points to 5
...   l = [1, 2] # this creates a local name l that points to [1, 2]
...
>>> i = 10
>>> l = [1, 2, 3]
>>> print(i)
10
>>> print(l)
[1, 2, 3]
>>> foo(i, l)
>>> print(i)
10
>>> print(l)
[1, 2, 3]

现在,如果您将 foo() 更改为变异 l,那就是另一回事了

>>> def foo(i, l):
...     l.append(10)
...
>>> foo(i, l)
>>> print(l)
[1, 2, 3, 10]

Python 3 的例子也是如此

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(i, l):
...   i = 5 # this creates a new variable which is also called i
...   l = [1, 2] # this changes the existing variable called l
...
>>> i = 10
>>> l = [1, 2, 3]
>>> print(i)
10
>>> print(l)
[1, 2, 3]
>>> foo(i, l)
>>> print(i)
10
>>> print(l)
[1, 2, 3]

【讨论】:

  • 哦,这实际上是我想说的更清楚的例子!
  • 我认为这可能是错误的。不会创建新变量,只是重新分配相同的参数变量。这是一个演示:ideone.com/LJt4AY。也就是说,我不明白这是对这个问题的回答(即为什么 Python 中有不可变对象)。
  • 答案是对的。问题和例子是错误的。
猜你喜欢
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 2012-11-18
相关资源
最近更新 更多