๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ | Python

Python_Call by Object Reference

by KASSID 2022. 1. 18.

๋ชฉ์ฐจ

    728x90

    ํŒŒ์ด์ฌ์˜ ๊ฐ์ฒด ์ฐธ์กฐ ๋ฐฉ์‹์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด์•˜๋‹ค.

    Call by Object Reference

    ๊ฐ์ฒด์˜ ์ฃผ์†Œ๊ฐ€ ํ•จ์ˆ˜๋กœ ์ „๋‹ฌ๋˜๋Š” ๋ฐฉ์‹์ด๋‹ค.

     

     

    ์•„๋ž˜์˜ ์˜ˆ์‹œ์™€ ํ•จ๊ป˜ ์•Œ์•„๋ณด์ž!

    def tomato(apple):
    	print(apple)	# [0]
        apple.append(1)	# 1 ์ถ”๊ฐ€
        print(tomato)	# [0,1]
        print(apple)	# [0,1]
    
    carrot = [0]
    tomato(carrot)
    print(carrot)
    #print(apple) apple์€ local๋ณ€์ˆ˜๋ผ์„œ ๋‹น์—ฐํžˆX
    
    --------
    # [0]
    # [0,1]
    # [0,1]
    # [0,1]

     

    ์œ„์˜ ๊ทธ๋ฆผ์„ ๋ณด์ž

    carrot์ด๋ผ๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋ฉด

    ํŠน์ • ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ์— ํ• ๋‹น์ด ๋œ๋‹ค.

     

    carrot์„ tomato๋ผ๋Š” ํ•จ์ˆ˜์— ๋„ฃ์–ด์„œ

    carrot์€ apple์ด ๋˜์—ˆ๋‹ค.

    ์ฆ‰, apple๋„ ๊ฐ™์€ ์ฃผ์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค!

     

    ๊ทธ์— ๋”ฐ๋ผ์„œ apple์— 1์„ ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ๊ฒƒ์€

    carrot์ด ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฒƒ ์—ญ์‹œ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์—

    carrot์„ printํ•ด๋ณด์•˜์„ ๋•Œ๋„ 1์ด ์ถ”๊ฐ€๋œ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

     

     

    ์กฐ๊ธˆ ๋‹ค๋ฅธ ์˜ˆ์‹œ๋ฅผ ๋ณด์ž!

    def tomato(apple):
    	print(apple)	# [0]
        apple.append(1)	# [0,1]
        apple = [2,3]	# apple์— [2,3] ํ• ๋‹น
        print(carrot)
        print(apple)
    
    carrot = [0]
    tomato(carrot)
    print(carrot)
    
    --------
    # [0]
    # [0, 1]
    # [2, 3]
    # [0, 1]

    ์ด๋ฒˆ์—๋Š” ์ค‘๊ฐ„์— apple์—๊ฒŒ ์ƒˆ๋กœ์šด ๊ฐ’์„ ํ• ๋‹น์‹œ์ผฐ๋‹ค.

     

    ์ด๋ฅผ ํ†ตํ•ด ์•Œ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์€

    ๊ฐ™์€ ์ฃผ์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋‹ค๊ฐ€ 

    ์ƒˆ๋กœ์šด ๊ฐ’์„ ํ• ๋‹น์‹œํ‚ค๋ฉด ์ƒˆ๋กœ์šด ์ฃผ์†Œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค.

     

     

     

    ๋Œ“๊ธ€