首頁  >  文章  >  後端開發  >  python有char類型嗎

python有char類型嗎

步履不停
步履不停原創
2019-07-02 09:31:2013258瀏覽

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影片教學

以上是python有char類型嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn