#file: wplan.py #get the obj's available public apis def getCmdsAllowd(obj): import re CFLAG = re.compile('^[a-z]') cmdsAllowd = [] for attr in vars(obj).values(): if hasattr(attr,'func_name') and re.match(CFLAG,attr.func_name): cmdsAllowd.append(attr.func_name) return cmdsAllowd class WPlanBase: def __getitem__(self, key): if hasattr(self, key): if hasattr(self, '_param'): return apply(eval('self.%s' % key), self._param[key]) else: return (eval('self.%s' % key))() else: error = "%s didn't has the '%s' method, available mehthods: %s" % \ (self.__class__, key, getCmdsAllowd(self.__class__)) raise Exception, error # parameters Class class WPlanParam(WPlanBase): def __init__(self, obj, paramsMap={}): self._obj = obj self._map = paramsMap obj._param = self def update(self, paramsMap): self._map.update(paramsMap) def __setitem__(self, key, val): self._map.update({key: val}) def __getitem__(self, funcName): coO, map = eval("self._obj.%s" % funcName).func_code, self._map return tuple([map.has_key(item) and map[item] or '' for item in coO.co_varnames[1:coO.co_argcount]])
将函数调用方式变为属性调用,便于业务模型的构建
比如你可以用sample['odata']['valideData']['kdata']来代替对应的3个函数调用, 可用于程序流程的设计 Sample file
# -*- coding: utf-8; -*- import wplan class Sample(wplan.WPlanBase): def __init__(self): pass def methodWithoutArg(self): print 'This is a sample' def methodWithOneArg(self, argOne): print 'Got arg: '+argOne if __name__ == '__main__': sample = Sample() param = wplan.WPlanParam(sample, {'argOne': 'OK'}) sample['methodWithoutArg'] sample['methodWithOneArg'] print param['methodWithOneArg'] param['argOne'] = 'OK Changed' sample['methodWithOneArg'] sample['with']