为什么python不重新引用这个现有的对象?

2024-10-04 01:25:04 发布

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

当我在Python中声明一个变量时,它引用一个对象。在本例中,我的对象是字符串“test”。当我将它与'ing123'连接起来时,变量a现在指向一个字符串对象'testing123'。不过,“testing123”的引用计数不会增加。为什么会这样?我认为python只需重新引用先前存在的“testing123”字符串对象。在本例中,它似乎正在创建另一个getrefcount无法识别的对象。我想我的问题是。。。。为什么会发生这种情况?我希望第二次调用getrefcount时返回5而不是4。你知道吗

from sys import getrefcount

b = 'testing123'
print getrefcount('testing123')
a = 'test'
a += 'ing123'
print getrefcount('testing123')
print a

打印。。。你知道吗

4
4
testing123

Tags: 对象字符串fromtestimport声明sys情况
2条回答

^{}获取所需行为的字符串:

>>> b = intern('testing123')
>>> getrefcount(b)
2
>>> a = 'test'
>>> a = intern(a+'ing123')
>>> getrefcount(b)
3
>>> a is b
True

不建议这样做。你知道吗

使用字典,它更安全。你知道吗

试试这个

dict = { 'testing123' : 4 }
a = 'test'
a += 'ing123'
print dict[a]

相关问题 更多 >