所以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这样的语言会有什么优点和缺点?
答案 0 :(得分:0)
您的示例不正确。 l
未在<{1}}范围之外进行更改。 foo()
内的i
和l
是指向新对象的新名称。
foo()
现在,如果您将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
Python 3的例子是相同的
>>> def foo(i, l):
... l.append(10)
...
>>> foo(i, l)
>>> print(l)
[1, 2, 3, 10]