我正在尝试生成一个继承自dict
,object
和另一个名为base
的类的基类。
类base
只包含一堆Web函数,几乎所有库中的类都将继承这些函数。
我想要的功能如下:
d = BaseService()
print d.a
如果属性a
不存在,我希望它调用一个函数并尝试获取该值。如果函数找不到该值,我希望引发标准错误:
AttributeError: 'BaseService' object has no attribute 'a'
我继续执行以下代码: class base(object): def _get(url,param_dict = None,securityHandler = None): param_dict = {'f':“json”} url_values = urllib.urlencode(param_dict) full_url = url +“?” + url_values res = urllib2.urlopen(url = full_url) return json.loads(res.read())
class BaseService(dict, base):
_url = None
_securityHandler = None
_proxy_url = None
_proxy_port = None
def __init__(self,
url,
securityHandler=None,
initialize=False,
*args, **kwargs):
self._url = url
self.update(*args, **kwargs)
super(BaseService, self).__init__()
self.__init()
def __setattr__(self, name, value):
self.__dict__[name] = value
#----------------------------------------------------------------------
def __init(self):
"""
private function that loads the service properties into the class
"""
res = self._get(url=self._url,
param_dict={"f":"json"})
self.update(*(), **res)
#----------------------------------------------------------------------
def __getitem__(self, key):
if hasattr(self, key) == False:
return None
val = dict.__getitem__(self, key)
return val
#----------------------------------------------------------------------
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
#----------------------------------------------------------------------
def __str__(self):# NOT WORKING AS EXPECTED
return json.dumps(self)
#----------------------------------------------------------------------
def __getattr__(self, name):
if name not in self.__dict__:
self.__init()
return self.__getattribute__(name)
#----------------------------------------------------------------------
def __repr__(self):
dictrepr = dict.__repr__(self)
return '%s(%s)' % (type(self).__name__, dictrepr)
#----------------------------------------------------------------------
def update(self, *args, **kwargs):
for k, v in dict(*args, **kwargs).iteritems():
self[k] = v
我尝试实施以下内容:
if __name__ == "__main__":
d = BaseService(url="https://www.arcgis.com/sharing/rest)
print str(d)
# prints '{"currentVersion":"4.1"}'
print d.currentVersion
# raises an error where __getitem__ isn't being called.
但是这给了我一些循环调用,这不好。