apppublic/appPublic/dictObject.py

113 lines
2.2 KiB
Python
Raw Normal View History

2020-06-08 08:00:42 +08:00
import json
from json import JSONEncoder
2019-07-16 16:33:07 +08:00
def multiDict2Dict(md):
ns = {}
for k,v in md.items():
ov = ns.get(k,None)
if ov is None:
ns[k] = v
elif type(ov) == type([]):
ov.append(v)
ns[k] = ov
else:
ns[k] = [ov,v]
return ns
2020-11-07 09:54:45 +08:00
class DictObject:
2020-06-03 11:10:05 +08:00
def __init__(self,**kw):
2020-11-07 09:54:45 +08:00
self.__kw = {}
2020-06-03 11:10:05 +08:00
for k,v in kw.items():
2020-06-08 08:00:42 +08:00
self.update({k:self.__DOitem(v)})
2020-06-03 11:10:05 +08:00
2020-11-07 09:54:45 +08:00
def update(self,kw):
self.__kw.update(kw)
2020-11-07 03:44:59 +08:00
def clear(self):
return self._kw.clear()
def get(self,name,default):
return self._kw.get(name,default)
def pop(self):
return self.__kw.pop()
def popitem(self,g):
return self.__kw.popitem(g)
2020-11-07 09:54:45 +08:00
def items(self):
return self.__kw.items()
def keys(self):
return self.__kw.keys()
def values(self):
return self.__kw.values()
def __getitem__(self,name):
return self.__kw.get(name)
def __setitem__(self,name,value):
self.__kw[name] = value
2020-06-03 11:10:05 +08:00
def __getattr__(self, name):
2020-11-07 09:54:45 +08:00
if self.__kw.get(name):
return self.__kw.get(name)
return None
def __str__(self):
return str(self.__kw)
2020-06-03 11:10:05 +08:00
2020-11-07 09:54:45 +08:00
def __expr__(self):
return self.__kw.__expr__()
2020-06-05 16:51:29 +08:00
2020-11-07 10:07:32 +08:00
def copy(self):
return {k:v for k,v in self.__kw.items()}
2019-07-16 16:33:07 +08:00
@classmethod
def isMe(self,name):
return name == 'DictObject'
2020-06-03 11:10:05 +08:00
def __DOArray(self,a):
b = [ self.__DOitem(i) for i in a ]
2019-07-16 16:33:07 +08:00
return b
2020-06-03 11:10:05 +08:00
def __DOitem(self, i):
if isinstance(i,DictObject):
return i
if isinstance(i,dict):
2020-07-12 16:03:29 +08:00
i = {k:v for k,v in i.items() if isinstance(k,str)}
2020-06-03 11:10:05 +08:00
try:
d = DictObject(**i)
return d
except Exception as e:
print("****************",i,"*******dictObject.py")
raise e
2020-11-07 09:54:45 +08:00
if type(i) == type([]) or type(i) == type(()) :
2020-06-03 11:10:05 +08:00
return self.__DOArray(i)
2019-07-16 16:33:07 +08:00
return i
2020-06-08 08:00:42 +08:00
class DictObjectEncoder(JSONEncoder):
def default(self, o):
return o._kwargs
2019-07-16 16:33:07 +08:00
def dictObjectFactory(_klassName__,**kwargs):
def findSubclass(_klassName__,klass):
for k in klass.__subclasses__():
if k.isMe(_klassName__):
return k
k1 = findSubclass(_klassName__,k)
if k1 is not None:
return k1
return None
try:
if _klassName__=='DictObject':
return DictObject(**kwargs)
k = findSubclass(_klassName__,DictObject)
if k is None:
return DictObject(**kwargs)
return k(**kwargs)
except Exception as e:
print("dictObjectFactory()",e,_klassName__)
raise e