파이썬의 함수는 일급 객체로 취급된다. 다음의 특징을 가졌을 때 일급 객체라고 부른다.
1. 변수에 할당할 수 있다.
철수 = print
철수('hi')
2. 함수의 인자로 전달 될 수 있다.
def hello():
print('hello')
A=hello
def single(A):
A()
single(hello)
3. 함수의 return 값이 될 수 있다.
앞에서 함수는 일급 객체의 성질로서 함수의 인자로 전달되기도 하고, 함수의 리턴 값이 되기도 한다고 했다. 이때, 함수를 인자로 받거나 또는 함수를 리턴하는 함수를 고위 함수라고 한다.
def debug(func):
def new_func():
print(f'{func.__name__}함수의 시작')
func()
print(f'{func.__name__}함수의 끝')
return new_func
def f1():
print('안녕하세요')
debug(f1)() #뒤에 붙은 ()는 new_func 실행
@debug
def f1():
print('안녕하세요')
f1()
def debug(func):
def new_function(*args, **kwargs):
print(f'{func.__name__}함수의 시작')
func(*args, **kwargs)
print('함수의 끝')
return new_function
@debug
def f1(val):
print(str(val)+'안녕하세요')
f1(10)
def debug(func):
def new_function(*args, **kwargs):
print(f'{func.__name__}함수의 시작')
result = func(*args, **kwargs)
print('함수의 끝')
return result
return new_function
@debug
def f1(val):
return val*(val+1)/2
print(f1(10))
@decorator1
@decorator2
@decorator3
진행 순서는 1 시작 -> 2시작 -> 3시작 -> 3끝 -> 2끝 -> 1끝
def add(func):
def new_function(*args, **kwargs):
result = func(*args, **kwargs)
return result + 100
return new_function
@add
def plus(a, b):
return a + b
print(plus(10, 20)) #출력 결과는 130
class debug:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print(f'{self.func.__name__} 함수 시작')
self.func()
print('함수 끝')
@debug
def f1():
print('안녕하세요')
f1()