Python & Django Day19 프레임워크
Fastcampus Python&Django 온라인 강의를 듣고 작성한 Class note입니다.
프레임워크, 라이브러리
차이점
라이브러리
필요한 기능들이 구현되어 있는 라이브러리에서 기능을 불러와서 사용하는 것이다.
직접 작성했기 때문에 프로그램 흐름의 전체를 이해하기 쉽다.
(예시)
1import requests
2response = requests.get("https://www.fastcampus.co.kr")
3response.text
프레임워크
이미 구성되어진 틀.
프레임워크 자체가 하나의 프로그램이다. 그러므로 실행 흐름이 결정되어 있고 필요한 기능들이 채워져 있다. 그러므로 라이브러리처럼 가져다 쓰는 것이 아니라 내가 필요한 기능으로 대체해서 사용하는 것이다.
실행 흐름이 이미 정해져 있기 때문에 어떤 방식과 흐름으로 코드가 실행되는지 파악하기 어렵다.
프레임워크 허들
- 정해진 약속대로 사용해야 한다.
- 흐름을 이해하기 어렵다.
수업 순서
- 간단한 계산기 프레임워크를 사용
- 계산기 프레임워크를 만들기
계산기 프레임워크
디렉토리 구조
-
main.py # 프레임워크 코드 파일
-
models
init.py
number.py # 숫자 포맷
operators.py # 연산자 등록하는 곳
-
main.py
1import operator as op
2
3try:
4 from models import operators
5except ImportError:
6 operators = None
7
8try:
9 from models import Number
10except ImportError:
11 Number = None
12
13default_operators = {
14 '+': op.add,
15 '-': op.sub,
16 '*': op.mul,
17 '/': op.truediv
18}
19
20operators = operators if operators else default_operators
21num_format = Number if Number else float
22
23def select_operator():
24 print("계산한 연산을 선택해주세요.")
25 for i, op in enumerate(operators):
26 print("{simbol} 연산".format(
27 simbol=op,
28 ))
29 try:
30 op = operators[input('연산자 입력 : ')]
31 except KeyError:
32 print("연산자를 바르게 입력해주세요")
33 return select_operator()
34 return op
35
36
37def select_number(n):
38 print("계산할 {n}번째 숫자를 선택해주세요.".format(n=n))
39 number = num_format(input('숫자입력 : '))
40 return number
41
42
43if __name__=='__main__':
44 print("지정 표현 맞춤형 계산기 프로그램 작동!")
45 while True:
46 print("종료는 Ctrl + c")
47 try:
48 op = select_operator()
49 num1 = select_number(1)
50 num2 = select_number(2)
51 except KeyboardInterrupt:
52 break
53 print('연산 결과는 {}입니다. '.format(op(num1, num2)))
init.py
1# __init__.py 를 폴더에 만들어야 모듈 인식할 수 있다.
2
3from .operators import operators # operators라는 dictionary 등록
4from .number import Number
number.py
1class Number(float):
2 num1 = {
3 0: '',
4 1: '일',
5 2: '이',
6 3: '삼',
7 4: '사',
8 5: '오',
9 6: '육',
10 7: '팔',
11 9: '구'
12 }
13
14 num2 = ['', '십', '백', '천', '만']
15
16 def __repr__(self):
17 str_num = str(self.real)
18 temp = str_num.split('.')
19 str_num = temp[0]
20 floating_value = '' if temp[1] == '0' else '.' + temp[1]
21
22 if len(str_num) > 5:
23 retrun str_num
24
25 result = ''
26 for i, n in enumerate(str_num):
27 result += ( self.num1[int(n)] + self.num2[len(str_num) -i -1] if self.num1[int(n)] else '')
28
29 if not result:
30 result = '영' + floating_value
31 return result + floating_value
32
33 def __str__(self):
34 return self.__repr__()
35
36 def __add__(self, other):
37 return Number(self.real + other.real)
38
39 def __sub__(self, other):
40 return Number(self.real - other.real)
41
42 def __mul__(self, other):
43 return Number(self.real * other.real)
44
45 def __truediv__(self, other):
46 return Number(self.real / other.real)
operators.py
1# 연산자 등록
2
3import operator
4
5def sharp(x, y):
6 return x + y + 100
7
8def custom_sub(x, y):
9 return x - y + (y + x)
10
11operators = {
12 "+" : operator.add, # operator.add(3, 4) : 3 + 4 실행
13 "-" : operator.sub,
14 "*" : operator.mul,
15 "/" : operator.truediv,
16 "#" : sharp,
17 "@" : custom_sub
18
19}