getattr
`getattr`函數屬于內建函數,可以通過函數名稱獲取
import statsout
def output(data, format="text"):
output_function = getattr(statsout, "output_%s" %format)
return output_function(data)
__call__
`__call__`方法用于實例自身的調用:
s = storage()
s['key'] = 'value'
print s(key) #調用__call__
__getattr__
從對象中讀取某個屬性時,首先需要從self.__dicts__中搜索該屬性,再從__getattr__中查找。
__setattr__
`__setattr__`函數是用來設置對象的屬性,通過object中的__setattr__函數來設置屬性:
__delattr__
`__delattr__`函數式用來刪除對象的屬性:
例子
完整例子可以參考微博API:http://github.liaoxuefeng.com/sinaweibopy/
def __init__(self, client, method, path):
self._client = client
self._method = method
self._path = path
#__call__函數實現_Executable函數對象為可調用的
def __call__(self, **kw):
method = _METHOD_MAP[self._method]
if method==_HTTP_POST and 'pic' in kw:
method = _HTTP_UPLOAD
return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw)
def __str__(self):
return '_Executable (%s %s)' % (self._method, self._path)
__repr__ = __str__
class _Callable(object):
def __init__(self, client, name):
self._client = client
self._name = name
def __getattr__(self, attr):
if attr=='get':
#初始化_Executable對象,調用__init__函數
return _Executable(self._client, 'GET', self._name)
if attr=='post':
return _Executable(self._client, 'POST', self._name)
name = '%s/%s' % (self._name, attr)
return _Callable(self._client, name)
def __str__(self):
return '_Callable (%s)' % self._name
__repr__ = __str__
而在源碼中,存在下面代碼片段:
def __getattr__(self, attr):
if '__' in attr:
return getattr(self.get, attr)
return _Callable(self, attr)
因此,加入我們初始化對象,并調用某函數如下:
新聞熱點
疑難解答
圖片精選