본문 바로가기

Application-level프로그래밍

[Python] 자주쓰는 list 등의 객체의 얕은 복사에 주의할 것

-------------------------------------------------------------------------
  target3Axis=[ [1,0,0], [0,1,0], [0,0,1] ]
  for i in range(numJoints):
    temp_axis=target3Axis
    transform3Axis(jointAngles[i],target3Axis,temp_axis,isDegree=True)
    jointLocalAxes[i]=np.array(temp_axis)
-------------------------------------------------------------------------
위 코드에서 target3Axis는 바뀌지 않을 것 같지만 바뀐다.
temp_axis 변수에 얕은 복사가 되고, temp_axis가 바뀌면서 같이 바뀌게 되는 것이다.

-------------------------------------------------------------------------
# 넘겨 받은 객체 a를 접근해서 수정하는 것은 되지만
# 넘겨 받은 객체 a를 다른 객체로 초기화 하면 호출 후에도 반영 안됨
def foo(a):

    a=[2]

    return


a=[1]

foo(a)

print a
-------------------------------------------------------------------------
위 코드에서 print a 의 결과는 '[1]' 이다.

-------------------------------------------------------------------------
# 함수내에서 초기화한 객체를 리턴할 수 있다.
# (복사를 해서 넘기는 지는 좀더 알아봐야됨.)
def foo(a):

    a=[2]

    return a


a=[1]

a=foo(a)

print a
-------------------------------------------------------------------------
위 코드에서 print a 의 결과는 '[2]' 이다.


-------------------------------------------------------------------------
# 전역 객체는 어디서 초기화 시켜도 반영된다. 
a=[1] # .py파일내에서 전역 변수 선언

def foo():

    global a

    a=[2]


foo()

print a
-------------------------------------------------------------------------
위 코드에서 print a 의 결과는 '[2]' 이다.



[참조: http://www.penzilla.net/tutorials/python/functions/]
...
Python passes all arguments using "pass by reference". However, numerical values and Strings are all immutable. Dictionaries and Lists on the other hand are mutable, and changes made to them by a called function will be preserved when the function returns. ...

'Application-level프로그래밍' 카테고리의 다른 글

Callback(콜백)  (0) 2012.01.31
[Python] 모듈, 패키지(Package) 사용하기  (0) 2011.12.27
[Python] 정적변수 사용하기  (0) 2011.11.22
List of numerical libraries  (0) 2011.11.13
[Python] Introduction  (0) 2011.09.23