Python / 객체(Object)와 변수(Variable)
객체(Object), 변수(Variable), 변수명(Variable Name)
메모리에 저장된 자료를 객체(object)라고 한다. 객체를 저장한 공간을 변수(Variable), 변수의 이름을 변수명(Variable Name)이라고 한다.
변수에 객체를 넣을 때 등호 '='을 이용한다. 등호 왼쪽에는 변수명, 등호 오른쪽에는 객체를 적는다.
예를 들어 다음은 객체 100을 x라는 이름의 변수에 저장하겠다는 뜻이다.
x = 100
변수명은 다음의 규칙을 지켜야 한다. 규칙에 맞지 않으면 에러가 난다.
- 키워드를 사용하면 안된다.
- 특수문자는 _만 허용한다.
- 숫자로 시작하면 안된다.
- 공백을 포함할 수 없다.
키워드는 다음으로 확인할 수 있다.
import keyword print( keyword.kwlist )
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
객체 출력
객체를 출력하는 대표적인 함수는 print()이다.
>>> x = 100 >>> print(x) 100
만약 존재하지 않는 변수라면 에러가 난다.
>>> print(xy) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> print(xy) NameError: name 'xy' is not defined
객체 삭제
del() 함수로 객체를 삭제한다.
>>> x=100 >>> print(x) 100 >>> del(x) >>> print(x) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print(x) NameError: name 'x' is not defined
존재하지 않는 변수를 삭제하려 하면 에러가 난다.
>>> del(xy) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> del(xy) NameError: name 'xy' is not defined
자료형(Data Type)
객체는 자료형을 갖는다. 자료형은 type() 함수로 확인할 수 있다.
>>> type(1) <class 'int'> >>> type(1.1) <class 'float'> >>> type(1+2j) <class 'complex'> >>> type('hello') <class 'str'> >>> type(True) <class 'bool'> >>> type([1,2,3]) <class 'list'> >>> type((1,2,3)) <class 'tuple'> >>> type({1,2,3}) <class 'set'> >>> type({1:10,2:20,3:30}) <class 'dict'>