Python 中 str 是如何实现的? [英] How is str implemented in Python?

查看:44
本文介绍了Python 中 str 是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>导入系统>>>sys.getsizeof("")40

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

解决方案

在 Python 中,字符串是对象,因此值是对象本身的大小.所以这个大小总是大于字符串本身的大小.

来自 stringobject.h:

typedef struct {PyObject_VAR_HEAD长 ob_shash;int ob_sstate;字符 ob_sval[1];/* 不变量:* ob_sval 包含 'ob_size+1' 元素的空间.* ob_sval[ob_size] == 0.* ob_shash 是字符串的哈希值,如果尚未计算,则为 -1.* ob_sstate != 0 如果字符串对象在 stringobject.c 中*实习"字典;在这种情况下,两个参考* 从 'interned' 到这个对象在 ob_refcnt 中 * 不计算 *.*/pyStringObject;

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

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

>>> import sys
>>> sys.getsizeof("")
40

Why does the empty string use so many bytes? Does anybody know what is stored in those 40 bytes?

解决方案

In Python strings are objects, so that values is the size of the object itself. So this size will always be bigger than the string size itself.

From 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;

From here you can get some clues on how those bytes are used:

  • len(str)+1 bytes to store the string itself;
  • 8 bytes for the hash;
  • (...)

这篇关于Python 中 str 是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆