🐹 λ³€μˆ˜μ˜ λ²”μœ„

λ―Όλ‹¬νŒ½μ΄μš°μœ Β·2024λ…„ 5μ›” 17일

🐹 파이썬 기초

λͺ©λ‘ 보기
14/19

πŸ’‘ 1. μŠ€μ½”ν”„

νŒŒμ΄μ¬μ—μ„œ λ³€μˆ˜μ˜ λ²”μœ„(scope)λŠ” ν•΄λ‹Ή λ³€μˆ˜κ°€ ν”„λ‘œκ·Έλž¨ λ‚΄μ—μ„œ 참쑰되고 변경될 수 μžˆλŠ” μ˜μ—­μ„ μ˜λ―Έν•œλ‹€. 파이썬의 λ³€μˆ˜ λ²”μœ„λŠ” 크게 λ„€ κ°€μ§€λ‘œ λΆ„λ₯˜λœλ‹€.

1-1. Locla (μ§€μ—­ λ³€μˆ˜)

Local ScopeλŠ” λ³€μˆ˜κ°€ ν•¨μˆ˜ λ‚΄μ—μ„œ μ •μ˜λ  λ•Œ ν•΄λ‹Ή ν•¨μˆ˜ λ‚΄λΆ€λ₯Ό μ˜λ―Έν•œλ‹€.

def local_example():
    local_var = "둜컬 λ³€μˆ˜"
    print(local_var)
    
local_example()
> 둜컬 λ³€μˆ˜
print(local_var)
> NameError: name 'local_var' is not defined

1-2. Enclosing (λ‘˜λŸ¬μ‹Ό λ²”μœ„)

Enclosing ScopeλŠ” λ‚΄λΆ€ ν•¨μˆ˜μ—μ„œ μ™ΈλΆ€ ν•¨μˆ˜μ˜ λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•  λ•Œ ν•΄λ‹Ή μ™ΈλΆ€ ν•¨μˆ˜ λ²”μœ„λ₯Ό μ˜λ―Έν•œλ‹€.

def outer_function():
    enclosing_var = "λ‘˜λŸ¬μ‹Ό λ²”μœ„ λ³€μˆ˜"

    def inner_function():
        print(enclosing_var)

    inner_function()
    
outer_function()
> λ‘˜λŸ¬μ‹Ό λ²”μœ„ λ³€μˆ˜

1-3. Global (μ „μ—­ λ²”μœ„)

Global λ²”μœ„λŠ” λ³€μˆ˜κ°€ μ΅œμƒμœ„ μˆ˜μ€€μ—μ„œ μ •μ˜λ  λ•Œ 전체 파일 λ‚΄μ—μ„œ ν•΄λ‹Ή λ³€μˆ˜λ₯Ό μ˜λ―Έν•œλ‹€.

global_var = 'κΈ€λ‘œλ²Œ λ³€μˆ˜'

def test_global():
  print(global_var)
  
test_global()
> κΈ€λ‘œλ²Œ λ³€μˆ˜
# μ „μ—­λ³€μˆ˜μ™€ μ§€μ—­λ³€μˆ˜
global_var = 10 # μ „μ—­λ³€μˆ˜

def test_global():
  global_var = 20 # μ§€μ—­λ³€μˆ˜
  print(global_var)

test_global()
print(global_var)
> 20
> 10
# μ „μ—­λ³€μˆ˜μ™€ μ§€μ—­λ³€μˆ˜
global_var = 10 # μ „μ—­λ³€μˆ˜

def test_global():
  global global_var # μ „μ—­λ³€μˆ˜λ₯Ό λ‚΄μž₯ ν•¨μˆ˜ λ‚΄μ—μ„œ μ‚¬μš©
  global_var = 20 # μ „μ—­λ³€μˆ˜λ₯Ό μˆ˜μ •
  print(global_var)

test_global()
print(global_var)
> 20
> 20

1-4. Built-in (λ‚΄μž₯ λ²”μœ„)

빌트인 μ˜μ—­μ€ 파이썬의 λ‚΄μž₯ν•¨μˆ˜μ™€ λͺ¨λ“ˆλ“€μ΄ μ†ν•˜λŠ” λ²”μœ„μ΄λ‹€. print(), len()κ³Ό 같은 ν•¨μˆ˜λ“€μ΄ ν•΄λ‹Ήλœλ‹€.

print(print)
print(len)
> <built-in function print>
> <built-in function len>
print(aaa)
> NameError: name 'aaa' is not defined

2. ν•¨μˆ˜μ˜ λ²”μœ„ 탐색 μˆœμ„œ

  1. Local scope
  2. Enclosing scope
  3. Global scope
  4. Built-in scope

μ§€μ—­ λ²”μœ„μ— λ™μΌν•œ μ΄λ¦„μ˜ λ³€μˆ˜κ°€ μ—†μœΌλ©΄ νŒŒμ΄μ¬μ€ λ‘˜λŸ¬μ‹Ό λ²”μœ„λ₯Ό ν™•μΈν•˜κ³ , κ·Έ λ‹€μŒμœΌλ‘œ μ „μ—­ λ²”μœ„, λ§ˆμ§€λ§‰μœΌλ‘œ λ‚΄μž₯ λ²”μœ„λ₯Ό ν™•μΈν•œλ‹€.
μ΄λ ‡κ²Œ λ³€μˆ˜μ˜ λ²”μœ„λ₯Ό μ΄ν•΄ν•˜κ³  κ΄€λ¦¬ν•˜λŠ” 것은 μ½”λ“œμ˜ 가독성과 μœ μ§€ λ³΄μˆ˜μ„±μ„ 높이고, 예기치 μ•Šμ€ 였λ₯˜λ₯Ό λ°©μ§€ν•˜λŠ” 데 μ€‘μš”ν•˜λ‹€.

profile
μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자

0개의 λŒ“κΈ€