源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python __setattr__、 __getattr__、 __delattr__、__call__用法示例

  • 时间:2021-06-12 04:38 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
[b]getattr[/b] `getattr`函数属于内建函数,可以通过函数名称获取
[url=http://github.liaoxuefeng.com/sinaweibopy/]http://github.liaoxuefeng.com/sinaweibopy/[/url]
[u]复制代码[/u] 代码如下:
class _Executable(object):     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__
而在源码中,存在下面代码片段:
[u]复制代码[/u] 代码如下:
class APIClient(object):     '''     API client using synchronized invocation.     '''     ...     def __getattr__(self, attr):         if '__' in attr:             return getattr(self.get, attr)         return _Callable(self, attr)
因此,加入我们初始化对象,并调用某函数如下:
[u]复制代码[/u] 代码如下:
client = APIClient(...) #会调用__getattr__函数,从而调用__call__函数 client.something.get()
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部