python에서의 함수
파이썬에서 함수는 1st citizen이다. 즉, 객체로 존재한다. 객체이기 때문에 변수 대입, 함수 파라미터 전달 등이 가능하다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
def hello():
print('This is hello function')
# 함수를 변수에 대입
hi = hello
print(type(hi))
print(hi)
hi()
==================<<실행결과>>==================
<class 'function'>
<function hello at 0x0000020C0DAAF9D8>
This is hello function |
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
def hello(word_parameter):
print('This is from hello function')
print(word_parameter)
def call_hello(function, args):
function(args)
# 함수가 다른 함수의 파라미터로 전달
call_hello(hello, 'This is from call_hello')
print('='*30)
hello('This is from hello')
==================<<실행결과>>==================
This is from hello function
This is from call_hello
==============================
This is from hello function
This is from hello |
cs |
중첩함수 (Nested function)
파이썬은 함수 안에 다른 함수를 정의하는 것이 가능하다. 여기에서 내부에 정의된 함수를 중첩함수라고 한다.
중첩함수는 해당 함수가 정의된 함수 내에서 호출 및 반환이 가능하다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
def outer_func():
print('outer_func call')
# 중첩 함수 정의
def inner_func():
return 'inner_func call'
# 중첩 함수 호출
print(inner_func())
outer_func()
==================<<실행결과>>==================
outer_func call
inner_func call
|
cs |
※ 중첩함수의 경우 외부에서는 호출이 불가하다.
1
2
3
4
5
6
7
8
9
10 |
inner_func()
==================<<실행결과>>==================
NameError Traceback (most recent call last)
<ipython-input-12-101a8a644acc> in <module>()
----> 1 inner_func()
NameError: name 'inner_func' is not defined
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
def outer_func():
def inner_func():
return 'inner_func call'
return inner_func
fn = outer_func()
print(fn)
print(fn())
==================<<실행결과>>==================
<function outer_func.<locals>.inner_func at 0x0000020C0DB41730>
inner_func call
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
def outer_func(num):
# 중첩 함수에서 외부 함수의 변수에 접근 가능
def inner_func():
# 10이 사라지지만 inner_func()가 10을 기억한다. => Closure
return 'This is from inner_func', num
return inner_func
fn = outer_func(10)
print(fn())
==================<<실행결과>>==================
('This is from inner_func', 10)
|
cs |
Closure or Closure function
- enclosing scope(외부 함수)의 변수가 소멸되더라도 해당 변수의 값을 기억하고 사용할 수 있는 함수
- 위의 예제에서 inner_func은 closure (∵ outer_func이 이미 호출 종료되어 num의 scope가 소멸 되었는데도 해당 값을 기억)
- closure의 사용
1. class를 사용하지 않고 객체지향적인 솔루션을 제공
2. 일반적으로 제공해야 할 기능(method)이 적은 경우에 closure를 사용하여 기능을 제공함
3. 그 외의 경우 class를 사용하여 구현
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
def get_power_of(n):
def power(x):
return x ** n
return power
power5 = get_power_of(5)
power8 = get_power_of(8)
print(power5(2)) #power5(2)가 호출 되었는데, power5가 5를 기억하고 있다.
print(power8(2)) #power8(2)이 호출 되었는데, power8이 5를 기억하고 있다.
==================<<실행결과>>==================
32
256
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
def get_power_of(x, n):
def power():
return x, n, x ** n
return power
power2 = get_power_of(2, 3)
print(power2)
print(power2())
==================<<실행결과>>==================
<function get_power_of.<locals>.power at 0x0000029D328EFB70>
(2, 3, 8)
|
cs |
반응형
'Python > Python Basic' 카테고리의 다른 글
Decorator_03 (Decorator Chaining, Method decoration, Decorator with parameters) (0) | 2017.09.30 |
---|---|
Decorator_02 (파라미터가 있는 함수 decorator & 모든 함수에 대한 decorator) (0) | 2017.09.30 |
Class] 2. 정보은닉(private, protected, public) (0) | 2017.06.15 |
Class] 1. __init__ & method (0) | 2017.06.15 |
1. Series (0) | 2017.05.30 |