1. Type 이란?
Programming에서 사용되는 모든 value 혹은 object 들의 종류 를 (data) type
이라고 부름.
수학에서 숫자의 종류(type)를 실수, 정수, 자연수 등으로 나누는 것을 생각하면 쉽다.
Programming에서는 문자들도 다루며, 여러 object를 묶어 하나로 처리하기도 하기 때문에 보다 다양한 type을 지원한다.
2. Programming에서 Type 이란?
Programming에서 특정 object가 어떤 type
인지가 결정되면 다음의 내용이 해당 type
에 따라 결정된다.
- 해당 object가 가질 수 있는 value들의 집합이 결정됨. (예를 들어
int
type이면 정수만을 값으로 가질 수 있음) - 해당 object를 operand(피연산자)로 가질 수 있는
operator(연산자)
들이 결정됨. (문자와 같은 type은 나눗셈 operator의 operand가 될 수 없음)
3. Python에서 Type 확인하기
Python의 모든 obj에 대해 해당 type을 확인하려면 다음과 같이 type
함수에 해당 object를 argument로 넣어주면 됨.
type(obj)
4. Python에서 Type의 분류
Python에서 많이 사용되는 표준데이터 type들은 다음과 같음 (기본적인 type들을 의미함).
- Numeric Type
int
: 정수 (integer)float
: 실수 (real number, floating point)complex
: 복소수 (complex)
- Boolean Type
bool
:True
와False
만을 값으로 가짐. (boolean)
- Sequence Type
str
: 글자 하나씩의 관점에서는 sequence이지만, 문자열을 위해 사용됨 (collection의 성질보다 텍스트를 위한 type 성격이 강함). text string 또는 string이라고 불림.list
: item의 index로 순서를 사용하는 sequence type의 대표. mutable임.tuple
: immutaple list라고 불림.
- Set Type
set
: 수학에서의 집합을 abstraction(중복되는 item이 없고, 순서가 의미가 없음). mutable임.frozenset
: immutable set에 해당.
- Dictionary Type (or Mapping Type)
dict
: key 와 value로 구성된 pair를 item으로 가지는 collection. key를 통해 value에 접근 (순서가 의미 없음).
- None Type
None
: none, void 등에 해당하는 type.- "없다"라는 것을 나타낸다.
- Binary Type
bytes
: immutable byte sequence. binary data를 위한 tuple이라고 생각하면 쉬움 (하나의 item이 1byte에 해당).bytearray
: mutable byte sequence. binary data를 위한 list라고 생각하면 됨.
https://dsaint31.tistory.com/569#Sequence
[Math] Sequence (수열) and Series (급수)
Sequence 수열, 열 이라고 불림. numbers나 objects 들이 순서를 가지고(ordered) 나열된 것을 가르킴. order(순서)가 의미를 가지며, (order가 다르기 때문에 )중복이 허용이 된다. 중복이 허용된다는 점과 순
dsaint31.tistory.com
[Python] mutable and immutable: Mutability
Python에서 Data Types를 구분짓는 중요 속성. Python에서 Object 는 id, type, value, reference count 를 가지는데, 이 중 value를 변경할 수 있는지를 나타내는 것이 바로 mutability임. Mutable인 type의 object(객체)는 자
ds31x.tistory.com
4.1. Numeric Type
arithmetic operator들과 함께 수를 처리하기 위한 type.
2022.08.31 - [.../Math] - [Math] 수(Number)의 종류
[Math] 수(Number)의 종류
Number의 종류는 다음과 같고, 이들은 각각 set을 이룸.2024.02.25 - [.../Math] - [Math] Class: set and proper class (클래스와 집합) [Math] Class: set and proper class (클래스와 집합)Class, Proper Class, and SetClass집합론 (Zer
dsaint31.tistory.com
https://dsaint31.me/mkdocs_site/CE/ch01/positive_number/#2-for-human
BME
양의 정수 표현하기 컴퓨터에서는 대부분 base-2 system (이진수)를 이용하여 positive integer를 표시함. 보다 많은 bit가 할당된 경우, 보다 큰 range의 수를 표현(구분)할 수 있음. 이진수 외에 다른 방식
dsaint31.me
https://dsaint31.me/mkdocs_site/CE/ch01/real_number/
BME
float double IEEE754 Scientific Notation Significant Figures Real Number 이진수로 decimal number 표현하기 실수를 bit로 표현하는 방법을 알기 이전에 2진수로 소수를 표현할 수 있어야 한다. 다음 URL을 참고 : 소수의
dsaint31.me
2022.12.28 - [Computer/CE] - [CE] Float 표현하기 : IEEE754
[CE] Float 표현하기 : IEEE754
실수 (Real Number) Representation과학이나 공학분야에서는 real number를 다룰 때, 아주 큰 값이나 아주 작은 값 등의 매우 큰 범위의 수를 다루는 경우가 많음.Real umber(실수)는 사람의 계산에선 주로 분수
dsaint31.tistory.com
https://bme808.blogspot.com/2022/11/ss-round-off-error-vs-truncation-error.html
SS : Round-off Error vs. Truncation Error
Round-off Error 컴퓨터에서 수치를 저장(혹은 표현)하는 데이터 타입의 한계(제한된 bit수)로 인한 에러. 제한된 비트에 수치를 저장하기 때문에 발생하며 Finite word-length effect, Finite wor...
bme808.blogspot.com
>>> i = int('7') # '7'이라는 문자열에 해당하는 integer (int type, 정수) 변수 i.
>>> type(i) # class int임을 확인할 수 있음.
<class 'int'>
>>> i
7
>>> f = 7.4 # float type
>>> type(f)
<class 'float'>
>>> f = 1. # 1. 은 1.0 과 같이 float type
>>> type(f)
<class 'float'>
>>> c = 1+2j # complex type
>>> type(c)
<class 'complex'>
Python에서 numeric type은 C, C++과 달리 boxed type임. (primitive data type이라는 개념이 python에선 없음)
>>> 7.0.__str__()
'7.0'
- int 와 float type의 literal 도 자신의 값을 나타내는 문자열을 반환하는 method를 가지고 있음.
4.2. Boolean Type
if
statement, while
statement 및 logical operator들과 자주 사용되는 type.
- Boolean Type의 object가 가질 수 있는 value는 단 두가지이며 모두 keywords임.
>>> b = True # keyword True, False 가 바로 boolean type이 가질 수 있는 값.
>>> type(b)
<class 'bool'>
>>> b = False
>>> type(b)
<class 'bool'>
>>> i = 1
>>> j = 2
>>> b = i<j or i==j # boolean expression using logical operator
>>> b
True
>>> type(b)
<class 'bool'>
Programming 세계에서 다양한 numeric value에서 0
만을 False
로 간주하고, 그 외의 수는 True
로 간주하는 관례가 있다.
>>> i = 0
>>> b = bool(i)
>>> b
False
>>> f = 8.1
>>> b = bool(f)
>>> b
True
다른 type의 object를 boolean type처럼 다루는 경우가 많으며, 이를 truthiness라고 한다. 다음 url을 참고 :
https://ds31x.blogspot.com/2023/07/python-truthiness.html
Python : Truthiness
1. 원래 정의 믿고 싶은 진실(belief) , 주관적 진실(assertion) 을 의미하는 truthiness 는 evidence(증거), logic, intellectual examination, fact 등과 상관 없이 "직감적으로" ...
ds31x.blogspot.com
boolean algebra와 logical operation에 대한 개념은 다음 url을 참고 :
https://dsaint31.me/mkdocs_site/CE/ch01/ch01_13_boolean_algebra
BME228
Boolean Algebra George Boole(1815-1864, 영국)이 고안한 logic을 다루는 algebra로 "True, False를 수학적인 영역으로 포함"시켜 참과 거짓을 1,0에 대입하고, AND, OR, NOT 등의 logical operation을 사용하여 논리적 동작(
dsaint31.me
4.3. String Type : str
문자열 (text데이터)을 처리하기 위해 사용되는 type.
String (문자열) str
의 경우,
character chr
의 묶음이며 item들의 순서가 의미가 있다는 점에서 Sequence type에 속하지만,
Text에 대한 abstraction이기 때문에 다양한 문자열 처리를 위한 기능이 많다.
때문에 Collection을 다루는 type들과 공통점을 가지나 문자열 자체를 다루기 위한 기능들을 주의해서 다루어야 함.
str
의 literal을 표시하기 위해'
(single quote) 나"
(double quote)로 해당 txt를 감싸준다.- 단 감싸주는 시작과 끝이 동일한 기호로 이루어져야 함.
- multi-line의 string은 three single quote 또는 three double quote로 묶어준다. (역시 시작과 끝이 같아야 함.)
다음 예를 확인.
>>> sq = 'single quote'
>>> dq = "double quote"
>>> ml = """multiline
... line1
... line2"""
>>> type(sq)
<class 'str'>
>>> type(dq)
<class 'str'>
>>> type(ml)
<class 'str'>
>>> ml
'multiline\nline1\nline2'
>>> print(ml)
multiline
line1
line2
- 위의 예에서
\n
과 같이 back slash로 시작하는 글자는 escape sequence라고 불리며 특수한 글자들을 표현함. \n
은 new line이라고 읽고, string에서 개행을 의미함.
글자 하나만을 다루는 char
도 있으나 길이가 1인 str
과 동일하다.
a_code = ord('a') # `a`글자에 해당하는 code 숫자 얻음.
a_chr = chr(a_code) # a_code에 해당하는 글자를 값으로 가지는 변수 a_chr
print(type(a_chr)) # `str` class로 나옴. 즉, 문자열임.
4.4. Collection Type
Collection type 은 하나의 이상의 object들을 포함하는 data type을 가리킴.
참고로, 구성하고 있는 각각의 object를 item 또는 element라고 부름.
Sequence type (list, tuple) , Set (set, frozenset), Mapping type (dict) 들은 여러 object들을 묶어놓은(grouping) data type으로서 이들은 모두 Collection type에 속함.
- Sequence type 중
list
는 square bracket을 사용하고tuple
은 parentheses를 사용하며, - Set type 중
set
은 curly bracket을, - Mapping type인
dict
는set
과 마찬가지로 curly bracket을 사용하지만 내부의 각 item이 colon으로 구분되는 key and value pair로 구성된다.
>>> l = ['one', 'two', 'three']
>>> type(l)
<class 'list'>
>>> l
['one', 'two', 'three']
>>> t = tuple(l)
>>> type(t)
<class 'tuple'>
>>> t
('one', 'two', 'three')
>>> s = set(l)
>>> s
{'one', 'two', 'three'}
>>> d = {l[0]: 0, l[1]: 1, l[2]: 2}
>>> d
{'one': 0, 'two': 1, 'three': 2}
>>> type(d)
<class 'dict'>
list
나tuple
은l[0]
,t[0]
와 같이 item의 순서에 해당하는 index를 square bracket에 기재하여 각 item에 접근이 가능함.dict
의 경우는 square bracket 안에 index 대신 key가 들어감. 위의 예에서는d['one']
으로 int0
을 값으로 가지는 item에 접근 가능.set
은 수학에서의 집합연산 (union, intersection, 포함여부)에 해당하는 연산과 같이 사용됨.
[Python] list (sequence type) : summary
list는 ordered mutable collection으로, collection을 위한 python data type들 중 가장 많이 사용된다. C에서의 array와 같이 가장 기본적인 collection임. 단, heterogeneous item을 가질 수 있으며, 여러 methods를 가지는
ds31x.tistory.com
[Python] dictionary (Mapping type) : basic
Python에서 dictionary는 key-value pair를 item으로 가지는 unordered mutable collection임. set과 함께 curly bracket (or brace)를 사용하는데, empty dictionary가 바로 {}로 표현됨 (dictionary가 set보다 많이 이용되는 점이 반
ds31x.tistory.com
[Python] set and frozenset
set(집합) : 특정 conditions를 만족시키는 구별 가능한(distinct) object의 collection. set의 중요한 수학적 특징은 특정 object가 set에 속하는지 아닌지를 명확히 판별(특정 conditions에 의해)할 수 있음. set에
ds31x.tistory.com
2023.07.21 - [.../Math] - [Math] Sequence (수열) and Series (급수)
[Math] Sequence (수열) and Series (급수)
Sequence 수열, 열 이라고 불림. numbers나 objects 들이 순서를 가지고(ordered) 나열된 것을 가르킴. order(순서)가 의미를 가지며, (order가 다르기 때문에 )중복이 허용이 된다. 중복이 허용된다는 점과 순
dsaint31.tistory.com
4.5 Binary Data Type for Python
Python에서 Binary data를 byte 단위 (1byte = 8bit)로 다루는데 사용되는 Data Type임.
[Python] bytes and bytearray: Binary Data for Python
Python에서 bytes와 bytearray는 binary data를 byte 단위 (1byte = 8bit)로 다루는데 사용되는 Data Type임. bytes: bytes 는 immutable byte sequence 로서 일종의 byte로 구성된 tuple에 해당 함. byte literal은 다음과 같이 b라
ds31x.tistory.com
참고
- Python에서는 모든 것이 object이기 때문에
C
나C++
의 primitive data type이 없음. - 즉
int
type의 모든 object는 해당 type과 관련된 method들을 가진 일종의 class의 instance라고 볼 수 있음.
2023.02.01 - [Programming] - [Programming] Primitive Data Type : C, C++, NumPy, Torch
[Programming] Primitive Data Type : C, C++, NumPy, Torch
Primitive Data Type이(Unboxed type)란?C, C++, NumPy, Torch, TensorFlow 등에서 사용되는 numeric data type들은보통 unboxed type이라고도 불리는 primitive data type들이다.unboxed type에서는할당된 메모리 bit들이 해당 numeric
dsaint31.tistory.com
Python이 dynamic language이지만, type annotation을 통해 보다 엄격하게 type을 고려한 프로그래밍이 가능함.
[Python] Type Annotation: 파이썬에서 변수 및 함수에 type 지정.
Python은 Dynamic language이기 때문에 variable은 여러 type object를 가르킬 수 있다.이는 매우 높은 유연성을 제공해주고, 작은 규모의 소스코드에서는 잘 동작한다. (특히 type에 대해 자유롭다보니 언어
ds31x.tistory.com
2023.06.11 - [Programming] - [Python] Dynamic Language vs. Static Language
[Python] Dynamic Language vs. Static Language
Python은 대표적인 dynamic langauge 이다. (흔히, dynamic language를 scripting language라고도 부름) Static (Typed) Language Programming Language들 중에서 comiler language들의 경우 대부분이 static language로서 variable을 사용
dsaint31.tistory.com
'Programming' 카테고리의 다른 글
[Python] Variable (and Object) (0) | 2023.06.13 |
---|---|
[Python] Arithmetic in Python and Augmented Assignment (0) | 2023.06.12 |
[Python] Expression vs. Statement (0) | 2023.06.12 |
[WSL] Install WSL (Windows Subsystem for Linux) (0) | 2023.06.12 |
[Python] Python 소개? (0) | 2023.06.12 |