Python 01: 가변객체와 불변객체란 무엇일까?

객체란 무엇일까? What is an object?

파이썬에서 객체 (Object) 란 세 가지 특징을 가지고 있다.
Every object has an identiy, a type, and a value in Python.

value type identity
객체의 value 는 변할 수 있다
가변 (mutable)
반대로 객체의 value가 변할 수 없는 것을
불변 (immutable)
int, str, dict 등등
객체의 데이터 타입
일종의 객체 생성자
객체의 아이디 값은 절대 변하지 않는다
메모리에서 객체의 주소라고 생각할 수 있다
type() 로 확인 가능 id() 로 확인 가능
a is b 로 일치불일치 여부 확인 가능



그리고 그 객체들은 생성자(클래스)에 따라 크게 가변객체(mutable)불변객체(immutable)로 나뉜다.
파이썬에서 가변객체란 value 값을 바꿀 수 있는 객체 object 를 뜻하고 불면객체란 값을 바꿀 수 없는 객체를 뜻한다. 밑에 있는 코드들을 보며 알아보자!

Each objects are classified into either mutable or immutable objects depending on user-defined classes.

가변객체 (mutable) 불변객체 (immutable)
list, dict, set, 등등... str, int, float, tuple, 등등...



가변객체와 불변객체 (Mutable and Immutable)

list_values = [1,2,3]
set_values = (10,20,30)
print(list_values[0])
print(set_values[0])```

Output:


Value 를 바꿔보기: Lists vs tuples

list_values = [1, 2, 3]
set_values = (10, 20, 30)
list_values[0] = 100
print(list_values)
set_values[0] = 100```

Output:

tuple 의 값을 바꾸면 타입에러가 생기는 것을 볼 수 있다. List 는 값을 바꿔도 에러없이 잘 실행된다.

We can see that when we try to change the tuple we get an error, but we don't have that problem with the list.


Tuple vs List Expanding

한국말로 해석하기 보단 영어로 바로 이해하는 것이 빠르고 효율적이기 때문에 제목은 영어로 쓰기로 했다.

list_values = [1, 2, 3]
set_values = (1, 2, 3)
print(id(list_values))
print(id(set_values))
print()
list_values += [4, 5, 6]
set_values += (4, 5, 6)
print(id(list_values))
print(id(set_values))```

Output:

위 코드에서는 listtuple 을 연장했을 경우의 차이점이다. listidentity 는 변화가 없다. 하지만 tupleidentity 는 변한다. 즉, list 를 연장하는 것엔 문제가 없지만, tuple 을 연장할 경우엔 완전히 새로운 tuple 이 생성되는 것을 알 수 있다. 그러므로 List 가 메모리 사용면에 있어서 tuple 보다 더 효율적이다.

We can see that the list identity is not changed, while the tuple identity is changed. Meaning that we have expanded out list, but created a completed new tuple. Thus, lists are more efficient than tuples.


Copying Mutable Objects by Reference (가변객체 copying)

values = [1,2,3]
values2 = values
print(id(values))
print(id(values2))
values.append(4)
print(values is values2)
print(values)
print(values2)```

Output:

파이썬에서 가변객체란 list, dictionary, set, 등등이 있다. 여기서 가변객체의 특징(헷갈리기 시작하는 부분)을 볼 수 있다. 위의 코드를 보면 valuesvalues2 에게 대입하고 같은 id 값을 가지고 있다. 즉, 두개의 다른 list 가 생성됐다고 생각할 수 있지만 둘은 하나의 메모리 저장값을 가리키고 있다는 뜻이다. 그러므로 values4를 추가로 붙여도 메모리에 같은 객체를 가리키고 있기 때문에 같이 변한다. is operator 는 두 객체의 id 값만 비교하기 때문에 True가 나오는 것이다.

Warning!

여기서 주의할점은 가변객체를 copy 할땐 shallow copy 가 필요한지 deep copy 가 필요한지 주의할 필요가 있다. shallow copy 란 위 코드와 같이 객체를 복사했어도 주소값이 같은 것을 말하는 것이고 deep copy 는 밑의 그림과 같이 메모리값이 다른 하나의 객체를 복사하는 것이다. shallow copy 와 deep copy 에 대해서는 다음 게시물에서 확인하자!!


source: https://sourcedexter.com/python-list-copy/

Copying Immutable Objects (불변객체 copying)

text = "파이썬"
text2 = text
print(id(text))
print(id(text2))
print(text is text2)
text += "은 재밌다!"
print(id(text))
print(id(text2))
print(text is text2)
print(text)
print(text2)```

Output:

불변객체란 int,str, float, tuple, 등등을 말한다. 위 코드를 보면 texttext2 는 같은 id 값을 갖고 있지만 text 에 변화를 주면 text2 와 다른 새로운 id 값을 갖는다. 즉, text 에 변화를 주면 새로운 id 값의 객체를 생성한다. 그러므로 서로 다른 객체이기 때문에 text 를 업데이트해도 text2 에는 영향이 없는 것을 볼 수 있다.

Conclusion

파이썬에서 가변객체와 불변객체는 상황에 따라 쓰임이 다르다. 뭐가 더 좋고 나쁘다를 떠나서 때에 따라 사용을 잘하는 것이 중요하다. 불변객체는 접근이 더 빠르지만 새로운 객체를 생성하기 때문에 더 높은 비용이 든다. 반면에 가변객체는 쉽게 바꿀수 있다는 장점이 있다.

Mutable and immutable objects are handled differently in python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy. Whereas mutable objects are easy to change.

좋은 웹페이지 즐겨찾기