python有char类型吗


本文摘自php中文网,作者步履不停,侵删。

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

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

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

1

2

3

4

5

>>> import sys

>>> sys.getsizeof('')

37

>>> sys.getsizeof('a')

38



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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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, 可以节省空间并且加快速度.

1

2

3

4

5

6

7

8

/* 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 都是这样实现的

1

2

3

4

typedef struct {

PyObject_HEAD

long ob_ival;

} PyIntObject;



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

相关教程推荐:Python视频教程

以上就是python有char类型吗的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

厉害了,30行Python代码爬取英雄联盟全英雄皮肤

Python实现求笛卡尔乘积方法详解

Python中eval函数作用

Python爬虫基础之网页组成解析

Python实现在两个字典中寻找相同点的方法(附代码)

Python简单计算文件md5值的方法示例

如何利用Python开发手机app

Python中sys模块的详细介绍(代码示例)

如何利用Python函数求导数

Python中关于装饰器的学习

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...