有几种方式可以考虑:
1.使用namedtuple和struct模块
关于struct模块不再多介绍,可参考:http://www.weizn.net/?post=197
namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性,在访问一些tuple类型的数据时尤其好用。因为struct在用unpack解析完字节流后返回的是tuple类型,若使用namedtuple来命名tuple可以让代码更容易读懂。举个例子:
from collections import namedtuple # 变量名和namedtuple中的第一个参数一般保持一致,但也可以不一样 Student = namedtuple('Student', 'id name score') # 或者 Student = namedtuple('Student', ['id', 'name', 'score']) students = [(1, 'Wu', 90), (2, 'Xing', 89), (3, 'Yuan', 98), (4, 'Wang', 95)] for s in students: stu = Student._make(s) print stu # Output: # Student(id=1, name='Wu', score=90) # Student(id=2, name='Xing', score=89) # Student(id=3, name='Yuan', score=98) # Student(id=4, name='Wang', score=95)
或者:
from collections import namedtuple Friend=namedtuple("Friend",['name','age','email']) f1=Friend('xiaowang',33,'xiaowang@163.com') print(f1) print(f1.age) print(f1.email) f2=Friend(name='xiaozhang',email='xiaozhang@sina.com',age=30) print(f2) name,age,email=f2 print(name,age,email)从Python发送struct的时候可以这样:
from collections import namedtuple import pickle # or cPickle, it's faster MyStruct = namedtuple("MyStruct", "sMark nPackLen nFlag nGisIp nPort sData sEnd") tuple_to_send = MyStruct(sMark="abcdef", nPackLen=...) #构建元组 string_to_send = pickle.dumps(tuple_to_send) #序列化2.使用Python ctypes模块http://www.weizn.net/?post=215
2 comments
[F8] [F8] [F8] [F8] [F8] [F8] [F8] [F8] [F8]
学习了,{smile:3}{smile:4}{smile:4}{smile:4}{smile:4}{smile:4}{smile:4}