문제 출처: https://dojang.io/mod/page/view.php?id=2433
파이썬 코딩 도장: 42.7 연습문제: 데코레이터로 매개변수의 자료형 검사하기
다음 소스 코드에서 데코레이터 type_check를 작성하세요. type_check는 함수의 매개변수가 지정된 자료형(클래스)이면 함수를 정상적으로 호출하고, 지정된 자료형과 다르면 RuntimeError 예외를 발생시
dojang.io
다음 소스 코드에서 데코레이터 type_check를 작성하세요. type_check는 함수의 매개변수가 지정된 자료형(클래스)이면 함수를 정상적으로 호출하고, 지정된 자료형과 다르면 RuntimeError 예외를 발생시키면서 '자료형이 다릅니다.' 에러 메시지를 출력해야 합니다. 여기서 type_check에 지정된 첫 번째 int는 호출할 함수에서 첫 번째 매개변수의 자료형을 뜻하고, 두 번째 int는 호출할 함수에서 두 번째 매개변수의 자료형을 뜻합니다.
-----
...
-----
@type_check(int, int)
def add(a, b):
return a + b
print(add(10, 20))
print(add('hello', 'world'))
내가 작성한 함수
def type_check(type1, type2):
def real_decorator(func):
def wrapper(a, b):
if (type(a) == type1) & (type(b) == type2):
r = func(a, b)
return r
else:
raise RuntimeError
return wrapper
return real_decorator
@type_check(int, int)
def add(a, b):
return a + b
print(add(10, 20))
print(add('hello', 'world'))
홈페이지 답안
def type_check(type_a, type_b):
def real_decorator(func):
def wrapper(a, b):
if isinstance(a, type_a) and isinstance(b, type_b):
return func(a, b)
else:
raise RuntimeError('자료형이 올바르지 않습니다.')
return wrapper
return real_decorator
배운 점
1. isinstance 함수
파이썬 인스턴스가 특정 데이터 타입인지 또는 특정 클래스인지를 함수이다. 첫번째 인수는 인스턴스명, 두번째 인수는 타입이나 클래스를 받는다.
https://docs.python.org/3/library/functions.html#isinstance
Built-in Functions — Python 3.11.0 documentation
Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer, a floating poin
docs.python.org
2. 에러 발생시킬 때 문구 작성을 동시에 할 수 있음
https://docs.python.org/ko/3/tutorial/errors.html
8. 에러와 예외 — Python 3.11.0 문서
8. 에러와 예외 지금까지 에러 메시지가 언급되지는 않았지만, 예제들을 직접 해보았다면 아마도 몇몇 개를 보았을 것입니다. (적어도) 두 가지 구별되는 에러들이 있습니다; 문법 에러 와 예외.
docs.python.org
'繩鋸木斷水滴石穿 > Python' 카테고리의 다른 글
[pandas] style로 데꾸(데이터프레임 꾸미기)하는 방법 (1) | 2023.08.13 |
---|---|
[Dash] 파이썬에서 Dash를 이용한 대시보드 구축하기 (0) | 2022.12.21 |
[GeoPandas] GeoPandas를 이용한 좌표 데이터 다루기 (1) | 2022.10.30 |
[pandas] map과 replace의 차이 (0) | 2022.07.31 |
[pandas] idxmax, idxmin: 행, 열별 최댓값 및 최솟값의 인덱스 찾기 (0) | 2022.03.29 |