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 None s = 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 = 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__

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

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()

python __setattr__, __getattr__, __delattr__, __call__的更多相关文章

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

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

  2. __setattr__,__getattr__,__delattr__

    class Foo: x = 1 def __init__(self,y): self.y = y def __getattr__(self,item): print("---->fr ...

  3. __getattr__ __delattr__ __setattr__ __getattribute__使用(重写python提供的错误信息)

    自己定义了这些attr 查找删除设置就会触发自己定义的逻辑,如果不重新,pyton会提供自己报错信息class Room: def __init__(self,name): self.name = n ...

  4. python中的__getattr__、__getattribute__、__setattr__、__delattr__、__dir__

    __getattr__:     属性查找失败后,解释器会调用 __getattr__ 方法. class TmpTest: def __init__(self): self.tmp = 'tmp12 ...

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

    一:最基本的属性操作 class Generic: pass g= Generic() >>> g.attribute= "value" #创建属性并赋值 > ...

  6. 类的专有方法(__getattr__和__setattr__、__delattr__)

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #http://www.360doc.com/content/15/0413/19/12067640_4629 ...

  7. python类内部方法__setattr__ __getattr_ __delattr__ hasattr __getattribute__ __getitem__(),__setitem__(), __delitem__()

    主要讲类的内部方法 __setattr__  __getattr_  __delattr__  hasattr  __getattribute__  __getitem__(),__setitem__ ...

  8. 第8.33节 Python中__getattr__以及__getattr__与__ getattribute__的关系深入剖析

    一. 引言 前面几节分别介绍了Python中属性操作捕获的三剑客:__ getattribute__方法.__setattr__方法.__delattr__方法,为什么__ getattribute_ ...

  9. python之 __getattr__、__getattr__、__getitem__、__setitem__ 使用

    python之 __getattr__.__getattr__.__getitem__.__setitem__ 使用 __getattr__内置使用点号获取实例属性属性如 s.name,自调用__ge ...

随机推荐

  1. js 更改head的title

    使用document.title = "hello"; 不能使用 $("title").text("dd");或者            $ ...

  2. Hibernate的配置文件以及用法

    一. 三大框架 Hibernate 1.安装hibernate插件至ecilpse 2.进行配置 2.1 主配置文件 <?xml version="1.0" encoding ...

  3. LinQ 基础

    LinQ全名:Linq to Sql,是一种数据库访问技术 常见的数据库访问技术: 1.ADO.NET 2.Entity Framework  框架 3.LinQ LinQ是高集成化的数据访问类,它会 ...

  4. android_Activity之Button_OnClickListener

    今天我们要讲的主要是四大组件之一Activity 什么是Android 的四大组件呢?接下来简单了解下. 1.Activity  Activity就是我们应用程序的界面,主要用来跟我们的用户进行交互的 ...

  5. php protobuff 使用

    http://hi.baidu.com/sing520/item/a6e98a3545fe1ef2e6bb7ad0 php 不支持uint32 不支持空结构 不支持package

  6. getpid 与 gettid 与 pthread_self

    获取进程的PID(process ID) #include <unistd.h> pid_t getpid(void); 获取线程的TID(thread ID) 1)gettid或者类似g ...

  7. AngularJS学习--- AngularJS中的模板template和迭代器过滤filter step2 step3

    1.AngularJS 模板---step2: mvc(Model-View-Controller)模式在后端用的比较多,在前端也是一样的常用; 在AngularJS中,一个视图是模型通过HTML模板 ...

  8. php字符串赋值到js的坑

    很早以前的一个比较坑的问题,今天又遇到了,记录一下,免得以后再次入坑. 把php赋值到view层时,如果不是直接渲染到页面,而是赋值给变量.字符如果有回车或者换行就会出现问题. 示例: <?ph ...

  9. Spring 4 官方文档学习(十二)View技术

    关键词:view technology.template.template engine.markup.内容较多,按需查用即可. 介绍 Thymeleaf Groovy Markup Template ...

  10. MVC+ajax权限管理

    不喜欢说废话,直接了当: 1.控制器 /// <summary> /// 获取列表 /// </summary> /// <returns></returns ...