[Python] 함수
Y
Yerim
def 함수_이름(매개변수):
수행할_문장1
수행할_문장2
...
return 리턴값def add(a, b): # a, b는 매개변수
return a+b
c = add(3, 4) # 3, 4는 인수
print(c) # 7
d = add(b=7, a=5) # 매개변수를 지정하여 호출하는 경우
print(d) # 12def 함수_이름(*매개변수):
수행할_문장
...def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(a=1) # {'a': 1}
print_kwargs(name='foo', age=3) # {'age': 3, 'name': 'foo'}# default1.py
def say_myself(name, age, man=True):
print("나의 이름은 %s 입니다." % name)
print("나이는 %d살입니다." % age)
if man:
print("남자입니다.")
else:
print("여자입니다.")
def add_and_mul(a, b):
return a+b, a*b# vartest.py
a = 1
def vartest(a):
a = a + 1
vartest(a)
print(a) # 1# vartest.py
def vartest(a):
a = a + 1
vartest(a)
print(a) # 오류# vartest_return.py
a = 1
def vartest(a):
a = a + 1 #
return a
a = vartest(a)
print(a)# vartest_global.py
a = 1
def vartest():
global a # global
a = a + 1
vartest()
print(a)함수_이름 = lambda 매개변수1, 매개변수2, ... : 매개변수를_이용한_표현식함수명 | 기능 | 예시 |
abs | 숫자의 절댓값 리턴 | abs(3) # 3 abs(-3) # 3 abs(-1.2) # 1.2 |
all | 반복 가능한 데이터 x를 입력값으로 받으며 x의 요소가 모두 참이면 True, 거짓이 하나라도 있으면 False를 리턴 | all([1, 2, 3]) # True all([1, 2, 3, 0]) # False all([]) # True |
any | 반복 가능한 데이터 x를 입력으로 받아 x의 요소 중 하나라도 참이 있으면 True를 리턴, x가 모두 거짓일 때만 False를 리턴 | any([1, 2, 3, 0]) # True any([0, ""]) # False any([]) # False |
# 함수를 변수에 할당
def say_hello(name):
return f"Hello {name}"
greet = say_hello
print(greet("Alice")) # 출력: Hello Alice
# 함수를 다른 함수의 인자로 전달
def greet_loudly(greeting_func):
return greeting_func("Alice").upper()
print(greet_loudly(greet)) # 출력: HELLO ALICE
# 함수를 반환하는 함수
def get_greeting_func():
def greet(name):
return f"Hello {name}"
greet = get_greeting_func()
print(greet("Alice")) # 출력: Hello Alice# 함수를 인자로 받는 함수
def apply_to_three(func):
return func(3)
def square(n):
return n ** 2
print(apply_to_three(square)) # 출력: 9
# 함수를 반환하는 함수
def apply_addr(n):
def add(x):
return x + n
return add
add_five = make_addr(5)
print(Add_five(3)) # 출력: 8
# map 함수는 함수와 반복 가능한 객체를 인자로 받아,
# 해당 함수를 각 요소에 적용한 결과를 반환하는 고차 함수
numbers = [1, 2, 3, 4]
squares = map(square, numbers)
print(list(squares)) # 출력: [1, 4, 9, 16]lambda arguments: expression# 숫자를 받아서 그 제곱을 반환하는 람다 함수
square = lambda x: x ** 2
print(square(5)) # 출력: 25
# 두 숫자를 더하는 람다 함수
add = lambda x, y: x * y
print(add(3, 4)) # 출력: 7numbers = [1, 2, 3, 4]
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # 출력: [1, 4, 9, 16]# 클로저가 아닌 경우
def outer_functions():
def inner_function():
return 100+100
return inner_function
# 클로저의 경우
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
inner = outer_function(100)
innter(200) # inner 입장에서 100을 변경할 수 있는 방법은 없다def simple_decorator(function):
def wrapper():
print("Before the functions call")
function()
print("After the function call")
@simple_decorator
def hello():
print("Hello, world!")
hello() # 데코레이터가 없는 상태에서는 simple_decorator(hello)()와 같다
simple_decorator(hello)() # 이전 wrapper()와 동일Before the function call
Hello, world!
After the function calldef simple_decorator(function):
def wrapper(1):
print("Before the functions call")
function()
print("After the function call")
return wrapper
@simple_decorator
def 합(1):
return sum(1)
합([1, 2, 3, '4'])def debug(function):
def new_function():
print(f'{function.__name__} 함수 시작')
function()
print(f'{function.__name__} 함수 끝')
return new_function
@debug
def sum_1_to_n(n):
return n * (n + 1) / 2
result = sum_1_to_n(30)
print(result)def debug(function):
def new_function(n):
print(f'{function.__name__} 함수 시작')
print(n)
print(f'{function.__name__} 함수 끝')
return new_function
@debug
def sum_1_to_n(n):
return n * (n + 1) / 2
result = sum_1_to_n(30)
print(result)sum_1_to_n 함수 시작
30
sum_1_to_n 함수 끝
Nonedef debug(function):
def new_function(*args, **kwargs):
print(f'{function.__name__} 함수 시작')
function(*args, **kwargs)
print(f'{function.__name__} 함수 끝')
return new_functiondef debug(function):
def new_function(*args, **kwargs):
print(f'{function.__name__} 함수 시작')
function(*args, **kwargs)
print(f'{function.__name__} 함수 끝')
return new_function
@debug
def sum_1_to_n(n):
return n * (n + 1) / 2
result = sum_1_to_n(30)
print(result)sum_1_to_n 함수 시작
sum_1_to_n 함수 끝
None@decorator1
@decorator2
...
@decoratorN
def function(*args, **kwargs):
passdef decorator1(function):
def new_function(*args, **kwargs):
print('첫 번째 데코레이터 시작')
result = function(*args, **kwargs)
print('첫 번째 데코레이터 끝')
return result
return new_function
def decorator2(function):
def new_function(*args, **kwargs):
print('두 번째 데코레이터 시작')
result = function(*args, **kwargs)
print('두 번째 데코레이터 끝')
return result
return new_function
def decorator3(function):
def new_function(*args, **kwargs):
print('세 번째 데코레이터 시작')
result = function(*args, **kwargs)
print('세 번째 데코레이터 끝')
return result
return new_function
@decorator1
@decorator2
@decorator3
def sum_1_to_n(n):
return n * (n + 1) / 2
result = sum_1_to_n(30)
print(f'result: {result}')첫 번째 데코레이터 시작
두 번째 데코레이터 시작
세 번째 데코레이터 시작
세 번째 데코레이터 끝
두 번째 데코레이터 끝
첫 번째 데코레이터 끝
result: 465.0def decorator1(function):
def new_function():
print('첫 번째 데코레이터 시작')
function()
print('첫 번째 데코레이터 끝')
return result
return new_function
def decorator2(function):
def new_function():
print('두 번째 데코레이터 시작')
function()
print('두 번째 데코레이터 끝')
return result
return new_function
def decorator3(function):
def new_function():
print('세 번째 데코레이터 시작')
function()
print('세 번째 데코레이터 끝')
return result
return new_function
@decorator1
@decorator2
@decorator3
def print_hello():
print('hello world!')
print_hello()첫 번째 데코레이터 시작
두 번째 데코레이터 시작
세 번째 데코레이터 시작
hello world!
세 번째 데코레이터 끝
두 번째 데코레이터 끝
첫 번째 데코레이터 끝
465.0def add(function):
def new_function(*args, **kwargs):
result = function(*args, **kwargs)
return result + 100
return new_function
@add
def plus(a, b):
return a + b
result = plus(10, 20)
print(f'result: {result}') # result: 130def add(n):
def decorator(function):
def new_function(*args, **kwargs):
result = function(*args, **kwargs)
return result + n
return new_function
return decorator@add(10)
def plus(a, b):
return a + b
result = plus(10, 20)
print(f'result: {result}') # result: 40class Debug:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
print(f'{self.function.__name__} 함수 시작')
self.function()
print(f'{self.function.__name__} 함수 끝')@Debug
def f1():
print('안녕하세요')
@Debug
def f2():
print('hello')
f1()
f2()f1 함수 시작
안녕하세요
f1 함수 끝
f2 함수 시작
hello
f2 함수 끝