Guest User

Untitled

a guest
Jan 10th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.09 KB | None | 0 0
  1. # 함수
  2.  
  3. ## 위치 인자
  4. 값을 순서대로 상응하는 매개변수에 복사하는 인자이다.
  5. ```python
  6. def menu(wine, entree, dessert):
  7. return {'wine': wine, 'entree': entree, 'dessert': dessert}
  8. ```
  9.  
  10. ## 키워드 인자
  11. 매개변수에 상응하는 이름을 인자에 지정할 수 있다.
  12. ```python
  13. menu(entree='beef', dessert='bagel', wine='bordeaux')
  14. ```
  15.  
  16. 위치인자와 키워드 인자는 섞어서 쓸 수 있다. 단 위치 인자와 키워드 인자로 함수를 호출한다면 위치 인자가 먼저 와야 한다.
  17. ```python
  18. menu('frontenac', dessert='flan', entree='fish')
  19. ```
  20.  
  21. ## 기본 매개변수값 지정
  22. ```python
  23. def menu(wine, entree, dessert='pudding'):
  24. return {'wine': wine, 'entree': entree, 'dessert': dessert}
  25. menu('chardonnay', 'chicken')
  26. ```
  27.  
  28. ## 위치 인자 모으기: *
  29. 함수의 매개변수에 \*를 사용하면 위치 인자 변수들을 튜플로 묶는다
  30.  
  31. ```python
  32. def print_args(*args):
  33. print('Positional argument tuple:', args)
  34. print_args() # ()
  35. print_args(3, 2, 1, 'wait!', 'uh...') # (3, 2, 1, 'wait!', 'uh...')
  36. ```
  37.  
  38. 매개변수에 맨끝에 \*args 를 써서 나머지 인자를 모두 취하게 할 수 있다.
  39.  
  40. ```python
  41. def print_more(required1, required2, *args):
  42. print('Need this one:', required1)
  43. print('Need this one too:', required2)
  44. print('All the rest:', args)
  45.  
  46. print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')
  47. ```
  48.  
  49. ## 키워드 인자 모으기: **
  50. 키워드 인자를 딕셔너리로 묶을 수 있다. 인자의 이름은 키고, 값은 이 키에 대응하는 딕셔너리 값이다.
  51.  
  52. ```python
  53. def print_kwargs(**kwargs):
  54. print('Keywor arguments:', kwargs)
  55. print_kwargs(wine='merlot', entree='mutton', dessert='macaron')
  56. # Keyword arguments: {'dessert': 'macaroon', 'wine': 'merlot', 'entree': 'mutton'}
  57. ```
  58.  
  59. 위치 매개변수와 \*args, \*\*kwargs를 섞어서 사용하려면 이들을 순서대로 배치해야 한다.
  60.  
  61. ## docstring
  62. 함수 몸체 시작 부분에 문자열을 포함시켜 문서를 붙일 수 있다.
  63.  
  64. ```python
  65. def echo(anything):
  66. 'echo returns its input argument'
  67. return anything
  68. ```
  69.  
  70. docstring은 길게 작성할수 있고, 서식을 추가할 수도 있다.
  71.  
  72. ```python
  73. def print_if_true(thing, check):
  74. '''
  75. Prints the first argument if a second argument is true.
  76.  
  77. The operation is:
  78. 1. Check whether the *second* argument is true.
  79. 2. If it is, print the *first* argument.
  80. '''
  81. if check:
  82. print(thing)
  83. ```
  84.  
  85. docstring은 help(*함수이름*)으로 출력할 수 있다.
  86. 서식없는 docstring을 그대로 보고 싶다면 print(*함수이름*.\__doc__) 으로 출력한다.
  87. \__doc__은 docstring의 내부 이름인 함수 내의 변수이다.
  88.  
  89. ## 함수는 객체이다
  90. 함수는 변수에 할당할 수 있고, 다른 함수에서 인자로 사용될 수 있으며 이를 반환하는것도 가능하다.
  91.  
  92. ```python
  93. def answer():
  94. print(42)
  95.  
  96. def run_something(func):
  97. func()
  98. run_something(answer) # 42
  99.  
  100. type(run_something) # <class 'function'>
  101. ```
  102.  
  103. ```python
  104. def add_args(arg1, arg2):
  105. print(arg1 + arg2)
  106. def run_something_with_args(func, arg1, arg2):
  107. func(arg1, arg2)
  108.  
  109. run_something_with_args(add_args, 5, 9) # 14
  110. ```
  111.  
  112. 또한 \*args, \*\*kwargs 인자와 결합하여 사용할 수 있다.
  113.  
  114. ```python
  115. def sum_args(*args):
  116. return sum(args)
  117. def run_with_positional_args(func, *args):
  118. return func(*args)
  119. run_with_positional_args(sum_args, 1, 2, 3, 4) # 10
  120. ```
  121.  
  122. 함수는 리스트, 튜플, 셋, 딕셔너리의 요소로 사용할 수 있다. 함수는 불변이므로 딕셔너리의 키로도 사용할 수 있다.
  123.  
  124. ## 내부함수
  125. 함수 안에 또 다른 함수를 정리할 수 있다.
  126.  
  127. ```python
  128. def outer(a, b):
  129. def inner(c, d):
  130. return c + d
  131. return inner(a, b)
  132. outer(4, 7) # 11
  133. ```
  134.  
  135. ## 클로져
  136. 클로져는 다른 함수에 의해 동적으로 생성된다. 그리고 바깥 함수로부터 생성된 변수값을 변경하고, 저장할 수 있는 함수이다.
  137. ```python
  138. def knights2(saying):
  139. def inner2():
  140. return "We are the knights who say: '%s'" % saying
  141. return inner2
  142.  
  143. a = knights2('Duck')
  144. b = knights2('Hasenpfeffer')
  145. ```
  146.  
  147. a, b의 타입은 함수이며 이들은 함수이지만 클로져이기도 하다.
  148. ```python
  149. type(a) # <class 'function'>
  150. type(b) # <class 'function'>
  151.  
  152. a # <function kights2.<locals>.inner2 at 0x10193e158>
  153. b # <function kights2.<locals>.inner2 at 0x10193e1e0>
  154. ```
  155.  
  156. 이들을 호출하면 knights2() 함수에 전달되어 사용된 saying을 기억하다.
  157. ```python
  158. a() # "We are the knights who say: 'Duck'"
  159. b() # "We are the knights who say: 'Hasenpfeffer'"
  160. ```
  161.  
  162. ## 익명 함수: lambda()
  163. ```python
  164. def edit_story(words, func):
  165. for word in words:
  166. print(func(word))
  167.  
  168. staris = ['thud', 'meow', 'thud', 'hiss']
  169.  
  170. def enliven(word): # 첫 글자를 대문자로 만들고 느낌표 붙이기
  171. return word.capitalize() + '!'
  172.  
  173. edit_story(stairs, enliven)
  174. ```
  175.  
  176. 위 예제를 람다로 바꾸면
  177. ```python
  178. edit_story(stairs, lambda word: word.capitalize() + '!')
  179. ```
  180.  
  181. 람다의 콜론(:)와 닫는 괄호 사이에 있는 것이 함수의 정의 부분이다.
  182. 콜백 함수를 정의하는 GUI에서 람다를 사용할 수 있다.
Add Comment
Please, Sign In to add comment