Warm tip: This article is reproduced from serverfault.com, please click

python-列表和char内存分配之间的区别

(python - Difference between list and char memory allocation)

发布于 2020-11-30 14:15:23
def f(b, a=[]):
    a.append(b)
    print('a : ', a)
f(1)
f(2)

# >> a : [1]
# >> a : [1, 2]

我以为变量'a'保留在内存中,因为GC或引用计数未激活。

def f(b, a=''):
    a += b
    print('a : ', a)

f('1')
f('2')

# >> a : 1
# >> a : 2

此功能的结果是不同的。每次调用函数时都会初始化一个变量。

调用函数后仍保留字典,集合,列表的存储器。但是int,字符串已清除。是不同的内存分配系统吗?

Questioner
PSW
Viewed
0
Aaj Kaal 2020-11-30 22:36:45

原因是列表是可变对象。在第一个调用中,a被初始化,在随后的调用中被引用。从下面可以看到,int和str是不可改变的:

>>> str1 = 'hello'
>>> id(str1)
1900958690736
>>> str1 = 'how r u'
>>> id(str1)   # is a different string now
1900958712176

为了实现你要寻找的东西,你可以使用:

def f(b, a=None):
    if not a:
        a = []
    a.append(b)
    print('a : ', a)
f(1) # a :  [1]
f(2) # a :  [2]