gpt4 book ai didi

python - python 在执行 `a = ' python'` 时为何以及在何处插入字符串,而源代码未显示?

转载 作者:行者123 更新时间:2023-11-28 16:36:41 25 4
gpt4 key购买 nike

我正在尝试学习在字符串对象的实现中使用的 python 的实习生机制。但是在 PyObject *PyString_FromString(const char *str)PyObject *PyString_FromStringAndSize(const char *str, Py_ssize_t size) 中,python 仅在其大小为 0 或 1 时才驻留字符串.

PyObject *
PyString_FromString(const char *str)
{
fprintf(stdout, "creating %s\n", str);------------[1]
//...
//creating...
/* share short strings */
if (size == 0) {
PyObject *t = (PyObject *)op;
PyString_InternInPlace(&t);
op = (PyStringObject *)t;
nullstring = op;
Py_INCREF(op);
} else if (size == 1) {
PyObject *t = (PyObject *)op;
PyString_InternInPlace(&t);
op = (PyStringObject *)t;
characters[*str & UCHAR_MAX] = op;
Py_INCREF(op);
}
return (PyObject *) op;
}

但对于像 a ='python' 这样的较长字符串,如果我修改 string_print 来打印地址,它与另一个字符串变量相同 b = ' python 。在上面标记为 [1] 的行中,当 python 创建一个字符串对象时,我打印了一段日志,显示在执行 a ='python' 时创建了多个字符串,只是没有 'python'。

>>> a = 'python'
creating stdin
creating stdin
string and size creating (null)
string and size creating a = 'python'
?
creating a
string and size creating (null)
string and size creating (null)
creating __main__
string and size creating (null)
string and size creating (null)
creating <stdin>
string and size creating d
creating __lltrace__
creating stdout
[26691 refs]
creating ps1
creating ps2

那么字符串 'python' 在哪里创建和驻留?

更新 1

请引用@Daniel Darabos 的评论以获得更好的解释。提出这个问题是一种更容易理解的方式。

下面是PyString_InternInPlace添加日志打印命令后的输出。

PyString_InternInPlace(PyObject **p)
{
register PyStringObject *s = (PyStringObject *)(*p);
fprintf(stdout, "Interning ");
PyObject_Print(s, stdout, 0);
fprintf(stdout, "\n");
//...
}
>>> x = 'python'
Interning 'cp936'
Interning 'x'
Interning 'cp936'
Interning 'x'
Interning 'python'
[26706 refs]

最佳答案

编译器将字符串文字转换为字符串对象。执行此操作的函数是 PyString_DecodeEscape,至少在 Py2.7 中,您还没有说您使用的是哪个版本。

更新:

编译器在编译的时候会实习一些字符串,但是发生的时候会很困惑。该字符串只需要包含标识符可以的字符:

>>> a = 'python'
>>> b = 'python'
>>> a is b
True
>>> a = 'python!'
>>> b = 'python!'
>>> a is b
False

即使在函数中,字符串文字也可以被保留:

>>> def f():
... return 'python'
...
>>> def g():
... return 'python'
...
>>> f() is g()
True

但如果他们有有趣的角色则不然:

>>> def f():
... return 'python!'
...
>>> def g():
... return 'python!'
...
>>> f() is g()
False

如果我返回一对字符串,它们都不会被驻留,我不知道为什么:

>>> def f():
... return 'python', 'python!'
...
>>> def g():
... return 'python', 'python!'
...
>>> a, b = f()
>>> c, d = g()
>>> a is c
False
>>> a == c
True
>>> b is d
False
>>> b == d
True

故事的寓意:实习是一种依赖于实现的优化,它取决于许多因素。了解它的工作原理可能很有趣,但永远不要依赖它以任何特定方式工作。

关于python - python 在执行 `a = ' python'` 时为何以及在何处插入字符串,而源代码未显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25266774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com