IT/Python

[Python] ν΄λ‘œμ €(Closure) ν”„λ‘œκ·Έλž¨

ITyranno 2023. 11. 14. 12:27
728x90
λ°˜μ‘ν˜•

 

 

 

 

ν”„λ‘œκ·Έλž˜λ° 세계λ₯Ό νƒκ΅¬ν•©μ‹œλ‹€.

 

 

 

 

<ν΄λ‘œμ €(Closure)>
 - ν•¨μˆ˜ μ•ˆμ— ν•¨μˆ˜λ₯Ό λ§Œλ“€μ–΄μ„œ μ‚¬μš©ν•˜λŠ” λ°©μ‹
 - ν•¨μˆ˜ μ•ˆμ— μžˆλŠ” ν•¨μˆ˜λŠ” λ°”κΉ₯μͺ½ ν•¨μˆ˜μ—μ„œ μ°Έμ‘°ν•΄μ„œ μ‚¬μš©ν•˜λŠ” λ°©μ‹μœΌλ‘œ μ ‘κ·Όν•©λ‹ˆλ‹€.
 - ν•¨μˆ˜ μ•ˆμ— ν•¨μˆ˜λŠ” μ‚¬μš©μ΄ λλ‚˜λ©΄ λ©”λͺ¨λ¦¬μ—μ„œ ν•΄μ œλ˜κΈ° λ•Œλ¬Έμ— μœ μš©ν•˜κ²Œ μ‚¬μš©ν•˜λ©΄ μ’‹μŠ΅λ‹ˆλ‹€.

 

 

 

 

 

ν΄λ‘œμ € ν•¨μˆ˜ μ •μ˜ν•˜κΈ°

 

### ν΄λ‘œμ € ν•¨μˆ˜ μ •μ˜ν•˜κΈ°
def outer_function(x) :
    print(f"#1 : x = {x}")
    ### λ‚΄λΆ€ ν•¨μˆ˜ μ •μ˜ : μ‹€μ œ μ‹€ν–‰λ˜λŠ” ν•¨μˆ˜
    def inner_function(y) :
        print(f"#2 : y = {y}")
        s = x + y
        print(f"#3 : s = {s}")
        return s
    print("#4 -------")
    return inner_function

 

 

 

ν΄λ‘œμ € ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°

 

 

### ν΄λ‘œμ € ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°
closure_exe = outer_function(10)
print(closure_exe)

# - closure_exeλŠ” inner_function 자체λ₯Ό 리턴받은 ν•¨μˆ˜λ₯Ό μ˜λ―Έν•¨

 

 

 

 

 

 

 

 

λ‚΄λΆ€ ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°

 

### λ‚΄λΆ€ ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°
result1 = closure_exe(5)
print(result1)

 

 

 

 

 

 

 

ν΄λ‘œμ €λ₯Ό μ΄μš©ν•˜μ—¬ λˆ„μ ν•© κ³„μ‚°ν•˜κΈ°

 

### ν΄λ‘œμ €λ₯Ό μ΄μš©ν•˜μ—¬ λˆ„μ ν•© κ³„μ‚°ν•˜κΈ°
# - μ‚¬μš©ν•¨μˆ˜λͺ… : outer_function(), inner_function2(num)
# - μ‚¬μš©λ³€μˆ˜ : total(λˆ„μ λœκ°’μ„ μ €μž₯ν•  λ³€μˆ˜)

def outer_function2() :
    total = 0
    print(f"#1 : total = {total}")
    def inner_function2(num) :
        ### nonlocal : ν΄λ‘œμ € κ΅¬μ‘°μ—μ„œλŠ” μƒμœ„ λ³€μˆ˜λ₯Ό λ‚΄λΆ€ ν•¨μˆ˜μ—μ„œ μ‚¬μš©λͺ»ν•¨
        #            : λ”°λΌμ„œ, nonlocal을 μ§€μ •ν•΄μ„œ μ •μ˜ν•˜λ©΄ μ™ΈλΆ€ μ˜μ—­μ˜ λ³€μˆ˜ μ‚¬μš©κ°€λŠ₯
        nonlocal total
        print(f"#2 : total = {total} / num = {num}")
        
        total += num
        print(f"#3 : total = {total} / num = {num}")
        
        return total
    print(f"#4-------------------------")
    return inner_function2

 

 

 

μƒμœ„ ν•¨μˆ˜ 호좜

 

### μƒμœ„ ν•¨μˆ˜ 호좜
res_fnc = outer_function2()
res_fnc

 

 

 

 

 

 

λ‚΄λΆ€ ν•¨μˆ˜ 호좜

 

### λ‚΄λΆ€ ν•¨μˆ˜ 호좜
rs_total = res_fnc(5)
print(rs_total)

 

 

 

 

 

 

 

λ‚΄λΆ€ ν•¨μˆ˜ 호좜

 

### λ‚΄λΆ€ ν•¨μˆ˜ 호좜
rs_total = res_fnc(10)
print(rs_total)

 

 

 

 

 

<쑰건뢀 ν΄λ‘œμ € ν•¨μˆ˜ ν”„λ‘œκ·Έλž˜λ°>

 

def outer_function3(condition) :
    def true_case():
        return "true_case ν•¨μˆ˜κ°€ ν˜ΈμΆœλ˜μ—ˆμŠ΅λ‹ˆλ‹€."

    def false_case():
        return "false_case ν•¨μˆ˜κ°€ ν˜ΈμΆœλ˜μ—ˆμŠ΅λ‹ˆλ‹€."

    # condition의 값이 True이면 true_caseν•¨μˆ˜ 호좜
    #                 False이면 false_caseν•¨μˆ˜ μ •μ˜
    rs = true_case if condition else false_case
    
    return rs

 

 

μƒμœ„ ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°

 

### μƒμœ„ ν•¨μˆ˜ ν˜ΈμΆœν•˜κΈ°
rs_function = outer_function3(True)
print(rs_function)

rs_functino = outer_function3(False)
print(rs_function)

 

rs_msg = rs_function()
print(rs_msg)

 

 

728x90
λ°˜μ‘ν˜•