Updated:

πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦Β Function Argument

파이썬의 λͺ¨λ“  λ©”μ„œλ“œλŠ” 기본적으둜 인자λ₯Ό call by value ν˜•νƒœλ‘œ 전달해야 ν•œλ‹€. ν•˜μ§€λ§Œ call by value 라고 ν•΄μ„œ ν•¨μˆ˜μ˜ λ™μž‘κ³Ό 원본 λ³€μˆ˜κ°€ μ™„μ „νžˆ 독립적인 것은 μ•„λ‹ˆλ‹€. 이것은 인자둜 μ–΄λ–€ 데이터 νƒ€μž…μ„ μ „λ‹¬ν•˜λŠ”κ°€μ— 따라 달라진닀. λ§Œμ•½ 인자둜 mutable(dynamic) 객체인 리슀트 λ³€μˆ˜λ₯Ό μ „λ‹¬ν–ˆλ‹€λ©΄, ν•¨μˆ˜μ˜ λ™μž‘μ— λ”°λ₯Έ κ²°κ³Όκ°€ κ·ΈλŒ€λ‘œ λ³€μˆ˜μ— λ°˜μ˜λœλ‹€. mutable κ°μ²΄λŠ” ν•¨μˆ˜ μŠ€μ½”ν”„ λ‚΄λΆ€ 지역 λ³€μˆ˜μ— μΉ΄ν”Ό λ˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— 이런 ν˜„μƒμ΄ λ°œμƒν•œλ‹€. λ”°λΌμ„œ 인자둜 λ¦¬μŠ€νŠΈμ™€ 같은 mutable 객체λ₯Ό μ „λ‹¬ν•˜λŠ” 것은 μˆ˜λ§Žμ€ λΆ€μž‘μš©μ„ 뢈러였기 λ•Œλ¬Έμ— μ§€μ–‘ν•˜λŠ”κ²Œ μ’‹λ‹€. μ•„λž˜ μ˜ˆμ‹œ μ½”λ“œλ₯Ό 보자.

""" function argument experiment with mutable vs immutable """
def function(args):
    args += 'in runtime'
    print(args)

# immutable object string
>>> immutable = 'immutable'
>>> function(immutable)
immutable in runtime 

>>> print(mmutable)
immutable

# mutable object list
>>> mutable = list('mutable')
>>> function(mutable)
['m', 'u', 't', 'a', 'b', 'l', 'e', ' ', 'i', 'n', ' ', 'r', 'u', 'n', 't', 'i', 'm', 'e']
>>> print(mutable)
['m', 'u', 't', 'a', 'b', 'l', 'e', ' ', 'i', 'n', ' ', 'r', 'u', 'n', 't', 'i', 'm', 'e']

λ™μΌν•œ ν•¨μˆ˜μ— λ™μΌν•˜κ²Œ 인자둜 μ‚¬μš©ν–ˆμ§€λ§Œ, immutable 객체인 λ¬Έμžμ—΄μ€ ν•¨μˆ˜μ˜ μ‹€ν–‰ 결과와 μ „ν˜€ λ¬΄κ΄€ν•œ λͺ¨μŠ΅μ΄λ‹€. ν•˜μ§€λ§Œ mutable 객체인 λ¦¬μŠ€νŠΈλŠ” ν•¨μˆ˜μ˜ μ‹€ν–‰ κ²°κ³Όκ°€ μŠ€μ½”ν”„ λ°”κΉ₯의 원본 λ³€μˆ˜μ— κ·ΈλŒ€λ‘œ λ°˜μ˜λ˜μ—ˆμŒμ„ 확인할 수 μžˆλ‹€. 이것은 λ¦¬μŠ€νŠΈκ°€ 기본적으둜 μ»¨ν…Œμ΄λ„ˆ 내뢀에 μ‹€μ œ 값이 μ•„λ‹Œ μ£Όμ†Œ 값을 κ°–κ³  있고, Resize() 연산을 톡해 μˆ˜μ •μ΄ κ°€λŠ₯ν•˜κΈ° λ•Œλ¬Έμ΄λ‹€. ν•œνŽΈ, immutable 객체의 경우 원본 μˆ˜μ •μ΄ λΆˆκ°€ν•˜κΈ° λ•Œλ¬Έμ— κ΄€λ ¨ μ—°μ‚° ν˜Ήμ€ λͺ…령을 λ§Œλ‚˜λ©΄ deepcopy κ°€ λ°œμƒν•œλ‹€.

πŸ“¦Β Packing/Unpacking

Leave a comment