如何在python中实现str?

use*_*720 4 python python-2.7 python-internals

>>> import sys
>>> sys.getsizeof("")
40
Run Code Online (Sandbox Code Playgroud)

为什么空字符串包含这么多字节?有人知道这40个字节中存储了什么吗?

Sal*_*lem 6

在Python中,字符串是对象,因此值是对象本身的大小。因此,此大小将始终大于字符串大小本身。

来自stringobject.h

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;
Run Code Online (Sandbox Code Playgroud)

从这里您可以了解有关如何使用这些字节的一些线索:

  • len(str)+1 用于存储字符串本身的字节;
  • 8个字节用于哈希;
  • (...)

  • 不管。源代码中有一条注释:“在典型系统上,使用`PyStringObject_SIZE`代替`sizeof(PyStringObject)`可以为每个字符串分配节省3个字节。” (2认同)