> 백엔드 개발 > 파이썬 튜토리얼 > Python에는 char 유형이 있습니까?

Python에는 char 유형이 있습니까?

步履不停
풀어 주다: 2019-07-29 09:18:45
원래의
13927명이 탐색했습니다.

Python에는 char 유형이 있습니까?

Python에는 char 유형이 없으며 문자도 문자열입니다.

Python에는 왜 전용 char 데이터 유형이 없나요?

복잡한 것보다 단순한 것이 낫습니다. Python에서 문자열의 각 문자가 차지하는 공간은 8비트입니다.

1

2

3

4

5

>>> import sys

>>> sys.getsizeof('')

37

>>> sys.getsizeof('a')

38

로그인 후 복사



보시다시피 널 문자는 37바이트를 차지하고, 길이가 1인 문자열 'a'는 38바이트를 차지합니다. memory.byte. 문자 a가 하나 더 있으면 바이트가 하나 더 있습니다.

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;

로그인 후 복사

각 문자는 ob_sval에 저장되며 나머지 36바이트를 차지합니다. 실제로 Python의 문자열 구현은 길이가 0 또는 1인 문자열, 즉 char를 저장할 수 있는 *interned라는 전역 변수를 사용하므로 공간을 절약하고 속도를 높일 수 있습니다.

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에는 포인터도 없고 "네이키드 데이터 구조"(비객체)도 없습니다. 심지어 가장 간단한 정수 정수도 이런 방식으로 구현됩니다.

1

2

3

4

typedef struct {

PyObject_HEAD

long ob_ival;

} PyIntObject;

로그인 후 복사



간단히 말하면, 이 디자인은 Python의 "모든 것을 만족시킵니다." 사물이다'와 '모든 것은 최대한 단순하다'는 디자인 철학을 가지고 있다.

관련 튜토리얼 권장사항: Python 비디오 튜토리얼

위 내용은 Python에는 char 유형이 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿