Python 中 str 是如何实现的?

编程入门 行业动态 更新时间:2024-10-10 03:23:22
本文介绍了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 是如何实现的?

本文发布于:2023-11-30 07:51:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   Python   str

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!