Python: call-by-reference or call-by-value?

반디·2023년 3월 6일
0

Python

목록 보기
3/11

A. Python is 'call-by-object reference' or 'call-by-assignment'

  • 함수 인자로 immutable object 를 넘겨주는 경우: call-by-value
    함수에 넘겨준 값이 immutable object(numbers, strings, tuples)이면 넘겨준 값을 바꿀 수 없으므로 call-by-value 라고 할 수 있습니다.

  • 함수 인자로 mutable object 를 넘겨주는 경우: call-by-reference
    함수에 넘겨준 값이 mutable object(list, dictionary, set)라면, 함수 안에서 object에 수행한 변경사항이 함수 밖에서도 적용됩니다.

# call by reference

def add_more(list):
	list.append(50)
	print("Inside Function", list)

# Driver's code
mylist = [10,20,30,40]

add_more(mylist)
print("Outside Function:", mylist)

Note
value나 container를 변수에 할당하는 경우, 이 변수는 object로 취급됨

a = "immutable"
b = "immutable"

c = ['mutable', 10, 20, 30]
d = ['mutable', 10, 20, 30]
 
print('immutable object')
print(f"a의 주소: {id(a)}")
print("b의 주소:", id(b))
print("same location?", a is b, '\n') #a와 b가 같은 주소에 저장되어있는지의 여부를 출력

print('mutable object')
print(f"c의 주소: {id(c)}")
print("d의 주소:", id(d))
print("same location?", c is d) #c와 d가 같은 주소에 저장되어있는지의 여부를 출력

참고문헌

profile
꾸준히!

0개의 댓글