Python变量的序列化与反序列化

文章介绍了Python中使用pickle模块进行序列化和反序列化的过程,包括将Python对象转换为bytes存储或传输,以及从bytes恢复原对象。同时提到了通过str构造函数转换bytes到str的注意事项,并展示了使用json模块在不同编程语言间传递对象的方法。
摘要由CSDN通过智能技术生成

Python变量的序列化与反序列化

将Python变量转换为可以存储或传输的形式的过程称之为序列化。

通过模块pickle进行序列化与反序列化

  • 序列化:模块pickle可以将任意类型的变量转换成bytes形式的变量,然后可以直接存储该bytes形式变量到文件中或者通过套接字传输该bytes形式变量。
  • 反序列化:直接从文件中读取该bytes形式变量或者通过套接字接受该bytes形式变量,然后模块pickle可以将bytes形式的变量转换成实际对应类型的变量。
  • 通过模块pickle将任意类型的变量转换成bytes形式的变量时,会记录原变量所对应类的位置信息;通过模块picklebytes形式的变量转换成实际对应类型的变量时,需要确保目标变量所对应的类的位置信息不变。
  • 使用模块pickle对Python变量进行序列化,也只能通过模块pickle进行反序列化。
import pickle

class Test():
	def __init__(self, info:str) -> NoneL
		self.info = info
	def print():
		print(self.info)

test = Test('test')
test_bytes = pickle.dumps(test)
# type of test_bytes is bytes
print(type(test_bytes))
test_object = pickle.loads(test_bytes )
test_object.print()

bytes类型变量转换成str类型变量

  • 直接通过str构造函数将bytes类型变量转换成str类型变量。

    对于bytes中的某些bytestr构造函数会将其转换为对应的字符而不是对应的ASCII码字符。

  • 再将转换后的str类型变量中的字符转换为对应的ASCII码字符。
import pickle

test = '"'
test_bytes = pickle.dumps(test)
test_bytes_str_ord = ''
for i in range(len(test_bytes )):
    byte_str = hex(test_bytes [i]).replace('0x', r'\x')
    if len(byte_str) == 3:
        byte_str = byte_str[0:2] + '0' + byte_str[2]
    test_bytes_str_ord  = test_bytes_str_ord + byte_str
test_bytes_str_ord = 'b\'' + test_bytes_str_ord + '\'' 

test_bytes = bytearray()
test_bytes_str_ord = test_bytes_str_ord[2:-1]
length = len(test_bytes_str_ord)
index = 0
while index < length:
    byte_str = test_bytes_str_ord[index+2:index+4]
    test_bytes= test_bytes + bytearray.fromhex(byte_str)
    index = index + 4
test_bytes = bytes(test_bytes)
test = pickle.loads(test_bytes)
print(test)

通过模块json进行序列化与反序列化

  • 序列化:模块json可以将有限类型的变量转换成str形式的变量,然后可以直接存储该str形式变量到文件中或者通过套接字传输该str形式变量。
  • 反序列化:直接从文件中读取该str形式变量或者通过套接字接受该str形式变量,然后模块json可以将str形式的变量转换成实际对应类型的变量。
  • 如果要在不同的编程语言之间传递对象,可以使用模块json对Python变量进行序列化。
  • 使用模块json序列化Python对象会稍显复杂,dump方法不知道如何将一个类转换成字符串,需要自行指定一个转换函数。
import json

dict_ = dict(one=1,two=2,three=3)
float_ = 3.14

dict_str = json.dumps(dict_)
float_str = json.dumps(float_)
# type of dict_str is str
print(type(dict_str ))
# type of float_str is str
print(type(float_str ))

dict_object = json.loads(dict_str)
float_object = json.loads(float_str)
# type of dict_object is dict
print(type(dict_object))
# type of float_object is float
print(type(float_object))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值