본문 바로가기
Programming/Python

Serialization, pickling - 직렬화

by Chan_찬 2020. 10. 7.
728x90
반응형

python - pickle, serialization

pickle

pickle은 python object를 가져와서 문자열표현으로 변환한다

pickling(serialization) : object -> bytes
unpickling(deserialization) : bytes -> object

>>> import pickle
>>> class Rectangle:
...     def __init__(self, width, height):
...             self.width=width
...             self.height = height
...             self.area = width * height
...
>>> rect = Rectangle(10, 20)
>>> type(rect)
<class '__main__.Rectangle'>

# pickling
>>> a=pickle.dumps(rect)
>>> a
b'\x80\x03c__main__\nRectangle\nq\x00)\x81q\x01}q\x02(X\x05\x00\x00\x00widthq\x03K\nX\x06\x00\x00\x00heightq\x04K\x14X\x04\x00\x00\x00areaq\x05K\xc8ub.'
>>> type(a)
<class 'bytes'>

# unpickling
>>> b=pickle.loads(a)
>>> b
<__main__.Rectangle object at 0x10d7a7b00>
>>> type(b)
<class '__main__.Rectangle'>

>>> b.area
200
728x90
728x90
BIG

'Programming > Python' 카테고리의 다른 글

Class, Object - 클래스, 객체  (0) 2020.10.16
exception - 예외처리  (0) 2020.10.13
lambda - 람다  (0) 2020.10.06
filter(), map()  (0) 2020.10.05
generator, iterator, yield  (0) 2020.09.30
Buy me a coffeeBuy me a coffee

댓글