티스토리 뷰
passed by assingnment
- 파라미터는 사실 object의 reference가 전달된다. (하지만 reference는 value로 전달됨)
- 파이썬의 모든 것은 객체이다.
- 파이썬의 data type은 immutable(불변)과 mutable(가변)이 있다.(int str같은 타입은 불변이고 , list dictionary같은 타입은 mutable이다.)
- 변수에는 객체의 주소를 담을 수 있는데, immutable한 데이터타입은 이 주소를 이용해 객체를 수정할 수 있지만, immutable한 데이터타입은 이 주소를 이용해도 객체를 수정할 수 없다.
stack overflow
- the parameter는 사실 an object의 reference가 전달된다.( 하지만 reference는 value로 전달됨 )
- 어떤 data type은 mutable이고 어떤것은 immutable하다.
=> If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
=> If you pass an imutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.
mutable object
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
=> Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed.
immutable object
def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
=> immutable is nothing we can do to change the contents of the string .
=> the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed.
참고
'파이썬' 카테고리의 다른 글
Flask-RESTX Swagger 사용법 (0) | 2022.01.05 |
---|---|
패키지 설치 에러 (0) | 2022.01.03 |
파이썬 인터프리터 환경설정 (0) | 2021.12.30 |