Python의 추상 클래스
Python에서는 추상 클래스를 사용하여 객체 지향 프로그래밍의 설계 원칙을 구현할 수 있다. 추상 클래스는 객체를 생성할 수 없는 클래스이며, 하나 이상의 추상 메서드를 포함한다. 이 클래스는 주로 상속을 통해 다른 클래스에서 구현되도록 사용된다.
from abc import *
class Friend(metaclass=ABCMeta):
def __init__(self, name):
self.name = name
@abstractmethod
def hobby(self):
pass
def printName(self):
print('name: ' + self.name)
class Tom(Friend):
def __init__(self, name, addr):
super().__init__(name)
self.addr = addr
def hobby(self):
print(self.addr + ' 거리를 걸어다님!')
def printAddr(self):
print('tom addr: ' + self.addr)
class James(Friend):
def __init__(self, name, addr):
super().__init__(name)
self.addr = addr
def hobby(self):
print(self.addr + ' 거리를 뛰어다님!')
def printAddr(self):
print('james addr: ' + self.addr)
tom = Tom("톰", "종로")
tom.printName() # name: 톰
tom.printAddr() # tom addr: 종로
tom.hobby() # 종로 거리를 걸어다님!
james = James("제임스", "강남")
james.printName() # name: 제임스
james.printAddr() # james addr: 강남
james.hobby() # 강남 거리를 뛰어다님!
예외 처리
Python에서는 예외 처리를 통해 코드 실행 중 발생할 수 있는 오류를 제어할 수 있다. try-except 블록을 사용하여 오류를 처리하고, 필요에 따라 finally 블록에서 반드시 실행되어야 하는 코드를 작성할 수 있다.
def divide(a, b):
return a / b
print('프로그램 시작')
try:
print('작업 중...')
# c = divide(5, 0)
f = open("c:/week/aa.txt")
except ZeroDivisionError:
print("두 번째 값은 0이면 안 됩니다.")
except FileNotFoundError:
print("불러올 파일이 없습니다.")
except Exception as e:
print("에러 발생:", e)
finally:
print('에러 유무와 상관없이 무조건 수행됨')
print('프로그램 종료')
파일 입출력
Python에서는 파일을 생성, 읽기, 쓰기, 그리고 복합 객체를 파일로 저장하거나 불러올 수 있다. 이 과정에서 with 구문을 사용하면 파일을 자동으로 닫을 수 있다.
import os
try:
# 파일 읽기
with open(os.getcwd() + r'\ftest.txt', mode='r', encoding='utf-8') as f:
print(f.read())
# 파일 쓰기
with open(os.getcwd() + r'\ftest2.txt', mode='w', encoding='utf-8') as f:
f.write('My friend2!')
f.write('Testing')
# 복합 객체 저장 및 불러오기
import pickle
with open('test.pickle', 'wb') as f:
phones = {'tom': '111-1111', '길동': '222-2333'}
li = ['마우스', '키보드']
t = (phones, li)
pickle.dump(t, f)
with open('test.pickle', 'rb') as f:
a, b = pickle.load(f)
print(a) # {'tom': '111-1111', '길동': '222-2333'}
print(b) # ['마우스', '키보드']
except Exception as e:
print('파일 처리 에러:', e)
dong = input('동을 입력하세요: ')
try:
with open('zipcode.txt', 'r', encoding='UTF-8') as files:
line = files.readline()
while line:
lines = line.split(chr(9))
if lines[3].startswith(dong):
print(f"{lines[0]} {lines[1]} {lines[2]} {lines[3]} {lines[4]}")
line = files.readline()
except Exception as e:
print('파일 처리 에러:', e)