str() 오버라이딩
def __str__(self):
return '{},{}'.format(self.x, self.y)
p1 = Point(3, 4)
print(str(p1)) # 3,4
def __add__(self, pt):
new_x = self.x + pt.x
new_y = self.y + pt.y
return Point(new_x, new_y)
p1 = Point(3, 4)
p2 = Point(5, 8)
p3 = p1 + p2 # 8,12
def __sub__(self, pt):
new_x = self.x - pt.x
new_y = self.y - pt.y
return Point(new_x, new_y)
def __mul__(self, pt):
new_x = self.x * pt.x
new_y = self.y * pt.y
return Point(new_x, new_y)
len() 오버라이딩
def __len__(self):
return self.x + self.y
인덱싱 오버라이딩
def __getitem__(self, index): # 인덱싱 오버라이딩 -> p4[0]
if index == 0:
return self.x
elif index == 1:
return self.y
else:
return -1
p4 = Point(10, 3)
print(p4[0]) # 10
print(p4[1]) # 3
print(p4[10]) # -1
오류가 발생되었을 때 별도의 처리를 하거나 무시하고 프로그램을 실행하는 것
오류가 발생될 것으로 예상되는 문자열을 try 블록에 코딩하고, try 블록에 코딩된 내용을 실행하다가 오류가 발생하면 더이상 try 블록의 내용을 실행하지 않고 해당 오류의 except 블록에 코딩된 내용을 실행
파이썬은 발생할 수 있는 모든 문제를 예외 클래스로 만들어놓음
모든 예외 클래스는 BaseException 클래스의 자식 클래스이며, BaseException 클래스의 자식 클래스 중 Exception 클래스는 모든 예외 클래스의 부모 클래스가 됨
try:
오류가 발생할 것으로 예상되는 문장
...
except 오류클래스명1:
해당 오류가 발생하면 실행할 문장
...
else:
오류가 없을 경우 실행할 문장
...
finally:
오류 발생 여부와 상관없이 무조건 실행할 문장
파일 열기
파일 변수 = open('파일이름', '파일 열기 모드')
input = open('./text.txt', 'r') # 텍스트 파일 열기 모드
input = open('./text.txt', 'rt') # t는 기본값
input = open('./apple.jpg', 'rb') # 바이너리 파일 열기 모드
with 문
readline(): 텍스트 파일을 한 줄씩 읽어서 처리. 파일이 종료되어 더이상 읽을 수 없으면 빈 문자열을 반환
with open('./output.txt', 'r') as file:
lines = []
while True:
line = file.readline()
if not line:
break
if len(line.strip()) != 0:
print(line, end='')
lines.append(line.strip())
print(lines) # ['김사과', '바나나']
readlines(): 전체라인을 모두 읽어서 각 라인 단위로 리스트에 요소로 저장
with open('./output.txt', 'r') as file:
lines = file.readlines()
print(type(lines)) # <class 'list'>
print(lines) #['김사과\n', '바나나\n']
외부 모듈 사용하기
import 모듈명
# 사용
모듈명.함수명()
from 모듈명 import 함수1, 함수2, ...
# 사용
함수명()
from 모듈명 import *
# 사용
함수명()
import 모듈명 as 별명
# 사용
별명.함수명()
배열이 필요한 이유
배열의 단점
# 1차원 배열: 리스트로 구현
arr_list = [1,2,3,4,5]
# 2차원 배열: 리스트로 구현
arr_list = [[1,2,3],[4,5,6],[7,8,9]]
# 인덱싱
print(arr_list[0]) # [1, 2, 3]
print(arr_list[0][0]) # 1
큐(Queue)
import queue
data_queue = queue.Queue() # 일반적인 큐
data_queue = queue.LifoQueue()
data_queue = queue.PriorityQueue()
data_queue.put('apple') # Enqueue
print(data_queue.get()) # Dequeue / 변수에 담을 수 있음
print(data_queue.qsize()) # 사이즈 출력