1.类的申明 class 类名(object): #默认是继承object类
2.类中的方法申明如 def getName(self,参数): #切记需要self
3.实体对象引用如 a=A();报错需要a=A.A();
以下是实体对象转dictionary类型总结:
第一种实体bean申明方式
# -*- coding: utf-8 -*-
class Person(object):
#可以有多个属性
def __init__(self, name, id):
self.name = name;
self.id = id;
第二种实体bean申明方式(类似于java bean)
# -*- coding: utf-8 -*-
class Person(object):
def set_id(self,id):
self.id=id;
def set_name(self,name):
self.name=name;
def get_id(self):
return self.id;
def get_name(self):
return self.name;
转换类
# -*- coding: utf-8 -*-
import json;
'''字典和实体bean相互转换以及字典转json字符串'''
class DictAndInterchange(object):
#实体bean转dict
def objectTodict(self,obj):
#convert object to a dict
d = {}
d.update(obj.__dict__)
return d;
#dict转实体bean obj=Obj(val1,val2....);无get/set方法
def dictToClass(self,d,class_):
args = dict((key.encode('ascii'), value) for key, value in d.items());
inst = class_(**args) #create new instance
return inst;
#dict转实体bean obj=Obj();get/set方法
def dictToClassV2(self,d,class_):
inst=class_();
for key in d:
setattr(class_, key, d[key])
return inst;
def dictToJsonStr(self,d):
#ensure_ascii=False表示中文不转ascii码
return json.dumps(d, sort_keys=True, indent=4, ensure_ascii=False);
测试类:
# -*- coding: utf-8 -*-
import Person;
import DictAndClassInterchange;
class MyTest(object):
if __name__ == '__main__':
mytest=DictAndClassInterchange.DictAndInterchange();
t={"id":"2","name":"名称"};
p1=mytest.dictToClass(t, Person.Person);
print "dict2Class字典方法转类对象:"+p1.name;
p=Person.Person("1","名称1");
o=mytest.objectTodict(p);
print "类转字典:"+o["name"];
print "字典转json:"+mytest.dictToJsonStr(o);
输出结果:
dict2Class字典方法转类对象:名称
类转字典:名称1
字典转json:{
"id": "1",
"name": "名称1"
}
测试类2:对应第二种bean
# -*- coding: utf-8 -*-
import Person;
import DictAndClassInterchange;
class MyTest(object):
if __name__ == '__main__':
mytest=DictAndClassInterchange.DictAndInterchange();
t={"id":"2","name":"名称"};
p2=mytest.dictToClassV2(t, Person.Person);
print "dictToClassV2字典方法转类对象:"+p2.name;
p=Person.Person();
p.set_id("1");
p.set_name("名称1");
o=mytest.objectTodict(p);
print "类转字典:"+o["name"];
print "字典转json:"+mytest.dictToJsonStr(o);
输出:
dictToClassV2字典方法转类对象:名称
类转字典:名称1
字典转json:{
"id": "1",
"name": "名称1"
}