파이썬 - call by object reference

함수의 종류

call by value, call by reference

분류 기준

  • 함수 호출에서의 인자 전달 방식
  • func(p1, p2) 에서의 인자 전달 방식
  • 파이썬은 call by value도, call by reference도 아닌 call by object reference 이다.

call by value (대표 언어: C)

  • 예시

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    #include <stdio.h>


    void change_value(num, new_num) {
    num = new_num;
    printf("%d in change_value\n", num);


    // global frame
    int main(void) {
    int num = 10;
    change_value(num, 20);
    printf("%d in main\n", num);

    return 0;
    }

    // result
    // 20 in change_value
    // 10
  • 해설) num = 10 정의되고, change_value() 함수 호출되어 스택프레임으로 num = 20이 되어도, 함수 호출이후 스택프레임이 사라지게 되어 num = 10이 호출된다.


call by reference (대표언어: C++, C#, JAVA)

  • 예시

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #include <stdio.h>


    void change_value(int *num, int new_num) {
    *num = new_num;
    printf("%d in change_value\n", *num)
    }


    // global frame
    int main(void) {
    int num = 10;
    change_value(&num, 20);
    printf("%d in main\n", num);

    return 0;
    }

    // result
    // 20 in change_value
    // 20
  • 해설) num = 10의 1byte 공간을 change_value() 함수 내 num이 참조(reference)하여, 스택프레임의 num = 20이 main 내 num에도 적용
    –> 스택 프레임 사라져도 num = 20 호출


call by object reference (대표언어: PYTHON)

  1. immutable인 경우

    • 예시

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      def change_value(num, new_num):
      num = new_num
      print("%d in change_value" % num)

      num = 10
      change_value(num, 20)
      print(num)

      # result
      # 20 in change_value
      # 10
    • 해설) change_value(num, 20)이 호출되면서 스택프레임으로 쌓여진 num이 20을 참조하게 되지만, print 출력 시 스택프레임이 사라지게 되면서 num 은 최종적으로 10을 참조하는 상태가 된다.
      call-by-object-reference

  1. mutable 인 경우

    • 예시

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      li = [1, 2, 3]

      def change_elem(li, idx, new_elem):
      li[idx] = new_elem

      change_elem(li, 1, 100)
      print(li)

      # result
      # [1, 100, 3]
    • 해설) change_elem 함수가 호출되어 스택 프레임이 쌓이게 되고, li[1]이 100을 참조하게 되면서 기존 2를 참조하는 선이 삭제된다. 결국 li는 [1, 100, 3]이 된다.
      KakaoTalk_20190312_171455107

    • list 데이터 저장 방식 (참조)
      KakaoTalk_20190312_171455487