温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中有没有char类型

发布时间:2020-11-11 14:31:53 来源:亿速云 阅读:220 作者:小新 栏目:编程语言

小编给大家分享一下python中有没有char类型,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

python没有char类型,一个字符也是字符串。

为什么在Python中没有专门的char数据类型呢?

简单胜于复杂。在 Python 中, 字符串中的每个字符占的空间大小是 8 bit.

>>> import sys
>>> sys.getsizeof('')
37
>>> sys.getsizeof('a')
38



可以看到, 空字符占用37个 byte, 长度为1的字符串 'a' 占内存 38个 byte. 多了一个字符 a 之后多了 1 个 byte.

在 Python 内部, 字符串是这样实现的

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;

每个 char 就是存在 ob_sval 里面的, 占大小 8bit. 余下的36个 byte 主要来自于宏 PyObject_VAR_HEAD. 实际上 python 的string实现还用到了一个叫 *interned 的全局变量, 里面可以存长度为 0 或 1 的字符串, 也就是 char, 可以节省空间并且加快速度.

/* This dictionary holds all interned strings. Note that references to
strings in this dictionary are *not* counted in the string's ob_refcnt.
When the interned string reaches a refcnt of 0 the string deallocation
function will delete the reference from this dictionary.
Another way to look at this is that to say that the actual reference
count of a string is: s->ob_refcnt + (s->ob_sstate?2:0)
*/
static PyObject *interned;



实际上在 python 里既没有指针也没有"裸露的数据结构" (非对象), 连最简单的整数 integer 都是这样实现的

typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;



总而言之, 这样的设计满足 python 的 "一切都是对象", "一切都尽可能simple" 的设计思想。

以上是python中有没有char类型的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI