2012-05-25 14 views

回答

6

一个例子是使用对象符号使用词典。例如,考虑一个字典

myDict = {'value': 1} 

通常在Python一个访问“值”变量作为

myDict['value'] 

这将在Python解释打印1。但是,有人可能希望使用myDict.value表示法。这可以通过使用下面的类来实现:

class DictAsMember(dict): 
    def __getattr__(self, name): 
     value = self[name] 
     if isinstance(value, dict): 
      value = DictAsMember(value) 
     return value 

my_dict = DictAsMember() 
my_dict['property'] = {'sub_property': 1} 

print(my_dict.property.sub_property) # 1 will be printed 
+1

应该是'value = self [name]'? – Darthfett

+0

@Darthfett是的,感谢您发现 - 我已更正示例代码。 – Chris

3

我需要为使用承载令牌的REST客户端执行此操作。我将Requests的Session对象封装到我自己的接口中,这样我就可以始终发送auth头文件,并且(更相关地)使用URL的路径将HTTP请求发送到同一个站点。

class requests_wrapper(): 
    client = requests.session(headers={'Authorization':'myauthtoken'}) 
    base_path = "http://www.example.com" 

    def _make_path_request(self, http_method, path, **kwargs): 
     """ 
     Use the http_method string to find the requests.Session instance's 
     method. 
     """ 
     method_to_call = getattr(self.client, http_method.lower()) 
     return method_to_call(self.base_path + path, **kwargs) 

    def path_get(self, path, **kwargs): 
     """ 
     Sends a GET request to base_path + path. 
     """ 
     return self._make_path_request('get', path, **kwargs) 

    def path_post(self, path, **kwargs): 
     """ 
     Sends a POST request to base_path + path. 
     """ 
     return self._make_path_request('post', path, **kwargs) 

    def path_put(self, path, **kwargs): 
     """ 
     Sends a PUT request to base_path + path. 
     """ 
     return self._make_path_request('put', path, **kwargs) 

    def path_delete(self, path, **kwargs): 
     """ 
     Sends a DELETE request to base_path + path. 
     """ 
     return self._make_path_request('delete', path, **kwargs) 

于是,我只能根据道路上的一个要求:

# Initialize 
myclient = requests_wrapper() 
# Make a get request to http://www.example.com/api/spam/eggs 
response = myclient.path_get("/api/spam/eggs") 
# Print the response JSON data 
if response.ok: 
    print response.json 
3

由于__getattr__only called when an attribute is not found,它可以定义一个替代的地方去寻找一个属性,或者,得到的默认值,类似于defaultdict的有用方式。

您也可以通过将对象的MRO中的所有查找委托给另一个对象来模拟基类高于其他对象的所有其他对象(尽管这样做可能会导致无限循环,如果另一个对象正在将该属性委托回)。

还有__getattribute__,这是相关的,因为它随时调用任何属性在对象上查找。

相关问题