dict参数初始化class对象
class Student(object):
def __init__(self):
self.name = ""
self.age = 0
...
@classmethod
def new_obj(cls, dataDict)
obj = cls()
for attr, val in dataDict.items():
setattr(obj, attr, val)
return obj
paramDict = dict(
"name": "ZhangSan",
"age": 18
)
s_obj = Student.new_obj(paramDict)
class对象转dict
class Student(object):
def __init__(self):
self.name = ""
self.age = 0
...
@property
def to_dict(self)
return dict(
name=self.name,
age=self.age,
...
)
s = Student(name="zs", age=19)
data = s.to_dict()
def props(self, model):
pr = {}
for name in dir(model):
if name == 'metadata':
continue
value = getattr(model, name)
if not name.startswith('__') and not callable(value) and not name.startswith('_'):
if isinstance(value, datetime):
timestamp = Timestamp()
timestamp.FromDatetime(value)
pr[name] = timestamp
else:
pr[name] = value
return pr