python __setattr__, __getattr__, __delattr__, __call__

getattr

`getattr`函数属于内建函数,可以通过函数名称获取

value = obj.attribute
value = getattr(obj, "attribute")

使用`getattr`来实现工厂模式

#一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出import statsout def output(data, format="text"):                           output_function = getattr(statsout, "output_%s" %format) return output_function(data)

__call__

`__call__`方法用于实例自身的调用:

class storage(dict):# __call__方法用于实例自身的调用#达到()调用的效果def __call__ (self, key):try:return self[key]except KeyError, k:return Nones = storage()
s['key'] = 'value'
print s(key) #调用__call__

__getattr__

从对象中读取某个属性时,首先需要从self.__dicts__中搜索该属性,再从__getattr__中查找。

class A(object):  def __init__(self):  self.name = 'from __dicts__: zdy'  def __getattr__(self, item):  if item == 'name':  return 'from __getattr__: zdy'  elif item == 'age':  return 26  a = A()
print a.name # 从__dict__里获得的
print a.age # 从__getattr__获得的  

__setattr__

`__setattr__`函数是用来设置对象的属性,通过object中的__setattr__函数来设置属性:

class A(object):def __setattr__(self, *args, **kwargs):  print 'call func set attr'  return object.__setattr__(self, *args, **kwargs) 

__delattr__

`__delattr__`函数式用来删除对象的属性:

class A(object):def __delattr__(self, *args, **kwargs):  print 'call func del attr'  return object.__delattr__(self, *args, **kwargs)  

例子

完整例子可以参考微博API:http://github.liaoxuefeng.com/sinaweibopy/

class _Executable(object):def __init__(self, client, method, path):self._client = clientself._method = methodself._path = path#__call__函数实现_Executable函数对象为可调用的def __call__(self, **kw):method = _METHOD_MAP[self._method]if method==_HTTP_POST and 'pic' in kw:method = _HTTP_UPLOADreturn _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 = clientself._name = namedef __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__

而在源码中,存在下面代码片段:

class APIClient(object):'''API client using synchronized invocation.'''... def __getattr__(self, attr):if '__' in attr:return getattr(self.get, attr)return _Callable(self, attr)

因此,加入我们初始化对象,并调用某函数如下:

client = APIClient(...)
#会调用__getattr__函数,从而调用__call__函数
client.something.get()

转载于:https://www.cnblogs.com/coder2012/p/4309999.html

python __setattr__, __getattr__, __delattr__, __call__相关推荐

  1. python中setattr用法_python 中__setattr__, __getattr__,__getattribute__, __call__使用方法

    object._getattr_(self, name) 拦截点号运算.当对未定义的属性名称和实例进行点号运算时,就会用属性名作为字符串调用这个方法.如果继承树可以找到该属性,则不调用此方法 实例in ...

  2. python 内置属性__setattr___python 自定义属性访问 __setattr__, __getattr__,__getattribute__, __call__...

    object._getattr_(self, name) __gettattr__:如果某个类定义了这个方法,并且在该类的对象的字典中又找不到相应的属性时候,那么该方法会被调用. 实例instance ...

  3. python __setattr__ , __getattr__

    Python Class 对象或类型通过内置成员 __dict__ 来存储成员信息. 我们还可以通过重载 __getattr__ 和 __setattr__ 来拦截对成员的访问,需要注意的是 __ge ...

  4. python面对对象编程-------5:获取属性的四种办法:@property, __setattr__(__getattr__) ,descriptor...

    一:最基本的属性操作 1 class Generic: 2 pass 3 4 g= Generic() 5 6 >>> g.attribute= "value" ...

  5. Python基础教程:__setattr__和__delattr__和__getattr__的用法

    学习python中有什么不懂的地方,小编这里推荐加小编的python学习群:895,817, 687 有任何不懂的都可以在里面交流,还有很好的视频教程pdf学习资料,大家一起学习交流! 一.__ se ...

  6. __getattribute__()、__getattr__()、__setattr__()、__delattr__()

    访问顺序: 实例的__getattribute__().Descriptor的__get__().实例的__dict__.只读Descriptor的__get__().实例的__getattr__() ...

  7. python __setattr__和__getattr__

    通过为dict添加__setattr__和__getattr__, 可以属性的语法访问dict的元素 http://www.2cto.com/kf/201507/413971.html class S ...

  8. python setattribute_python __setattr__ , __getattr__ , __setattribute__ 防止死循环 | 学步园

    Python Class 对象或类型通过内置成员 __dict__ 来存储成员信息. 我们还可以通过重载 __getattr__ 和 __setattr__ 来拦截对成员的访问,需要注意的是 __ge ...

  9. Python__getattr__、__setattr__、__delattr__、__getitem__、__setitem__、__getattribute__方法的理解

    1. __getattr__(self, item): 在访问对象的item属性的时候,如果对象并没有这个相应的属性,方法,那么将会调用这个方法来处理...这里要注意的时,假如一个对象叫fjs,  他 ...

  10. __setattr__,__getattr__,__getattribute__

    1,__getattribute__ 当实例调用某个属性或方法时,首先会调用__getattrbute__,也就是相当于默认调用该方法(隐含默认调用,无论何种情况,均会调用此方法). class Te ...

最新文章

  1. Android 中文API (65) —— BluetoothClass[蓝牙]
  2. tomcat内存占用过高_Tomcat 性能调优之 JVM 调优
  3. 前端常见跨域解决方案
  4. PHP判断远程url是否有效的几种方法
  5. VS2012番茄助手安装破解教程
  6. requests+正则表达式爬取豆瓣读书top250
  7. kali系统扫描ftp服务器,FileZilla的使用方法及kali系统ftp服务的安装
  8. 论文的字数是怎么算的
  9. 离散数学学习笔记----命题逻辑的推理理论
  10. 微软亚洲研究院院长换帅!复旦校友周礼栋博士升任新院长
  11. 高德地图API调用自定义地图使用
  12. 如何减少电气设备漏电问题,其解决方案有哪些?
  13. 监控系统首选DNS服务器,监控windows DNS服务器
  14. 法里昂第一大学一座大楼楼顶爆炸起火 致至少3人伤
  15. 如何在安卓计算机里边隐藏游戏,安卓手机如何隐藏应用程序,来看看吧
  16. 疫情在家,全球 3万个景区 VR全景图,免费看。
  17. 部署DNS从服务失败,nslookup访问www.linuxprobe.com失败
  18. 【MFC】 多国语言设置
  19. 基于SSM的新闻管理系统的设计与实现 毕业论文+项目源码及数据库文件、
  20. 生成函数(母函数)——目前最全的讲解

热门文章

  1. no talloc stackframe at ../source3/param/loadparm.c:4864, leaking memory
  2. 盘点前 10 名的免费跨浏览器测试工具
  3. xdebug+webgrind
  4. Python开发环境的搭建(win7)
  5. 七,OpenERP 移库操作模块
  6. HTML 中Doctype简单解析
  7. Android的NDK开发(2)————利用Android NDK编写一个简单的HelloWorld
  8. 我的5年Python7年R,述说她们的差异在哪里?
  9. SPSS时间序列分析
  10. html选择区域高亮,css+js实现部分区域高亮可编辑遮罩层