python中关于序列化问题

序列化:我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思

序列化例子:

import  json  
import cPickle  
__author__ = 'bintian.xbt'  
d = dict(name='xbt',age=20,score=99)  
son = json.dumps(d)  
print son  
class student(object):  
    def __init__(self,name,age,score):  
        self.name = name  
        self.age  = age  
        self.score= score  

def student2dict(std):  
    return {  
        'n':std.name,  
        'a':std.age,  
        's':std.score  
    }  

def dic2student(d):  
    return student(d['n'],d['a'],d['s'])  

s = student('xbt',30,100)  
json_s = json.dumps(s,default=student2dict)  
print json_s  
std = json.loads(json_s,object_hook=dic2student)  
print std  
print std.age,std.name,std.score  

s = student('xbt',30,100)  
pickle_s = cPickle.dumps(s)  
print pickle_s

输出:

D:\Python27\python.exe D:/py/webstats/webstats/test_json_pickle.py

{"age": 20, "score": 99, "name": "xbt"}

{"a": 30, "s": 100, "n": "xbt"}

<main.student object at 0x0274ABD0>

30 xbt 100

ccopyreg reconstructor p1 (cmain student p2 c__builtin object p3 NtRp4 (dp5 S'age' p6 I30 sS'score' p7 I100 sS'name' p8 S'xbt' p9 sb.

Process finished with exit code 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值