함수를 둘러싼 환경을 유지하고 다시 꺼내서 사용하는 함수
def calc():
a = 3
b = 5
def mul_add(x):
return a * x + b
print(f"{locals()['a'], locals()['b'] = }")
return(mul_add)
c = calc()
print(c(1), c(2), c(3), c(4), c(5))
def calc():
a = 3
b = 5
return lambda x: a * x + b
c = calc()
print(c(1), c(2), c(3))
def calc():
a = 3
b = 5
total = 0
def mul_add(x):
nonlocal total
print(total)
total = total + a * x + b
print(total)
return mul_add
c = calc()
c(1)
c(2)
def outer():
x = 100
def inner(y):
nonlocal x
return x+y
return inner
foo = outer()
foo(5)
'프로그래밍 > Python' 카테고리의 다른 글
제너레이터(Generator) (0) | 2024.08.12 |
---|---|
Python - 클래스 속성과 메서드 사용 (2) | 2023.11.25 |
Python - 인스턴스 변수 vs 정적변수 (0) | 2023.11.25 |
Python - 클래스 생성자 (2) | 2023.11.25 |
Python - 클래스 (1) | 2023.11.25 |