python有char类型吗-Python教程

资源魔 34 0

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视频教程

以上就是python有char类型吗的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题

抱歉,评论功能暂时关闭!