# 例子在原来的基础上简化了一下,排除依赖和干扰,详细参见原项目
class UrlGenerator(object):
def __init__(self, root_url):
self.url = root_url def __getattr__(self, item):
if item == 'get' or item == 'post':
print self.url
return UrlGenerator('{}/{}'.format(self.url, item)) url_gen = UrlGenerator('http://xxxx')
url_gen.users.show.get >>> http://xxxx/users/show

充分利用getattr会在没有查找到相应实例属性时被调用的特点,方便的通过链式调用生成对应的url,源代码中在碰到http method的时候返回一个
可调用的对象更加的优雅,链式的操作不仅优雅而且还能很好的说明调用的接口的意义(restful的接口啦)。

既然能通过定制类的getattr自定义方法来实现一些优雅的功能,自然我们也要对它有一些了解,包括和它相似的自定义方法getattribute

1. 用作实例属性的获取和拦截

当访问某个实例属性时, getattribute会被无条件调用,如未实现自己的getattr方法,会抛出AttributeError提示找不到这个属性,如果自定义了自己getattr方法的话,方法会在这种找不到属性的情况下被调用,比如上面的例子中的情况。所以在找不到属性的情况下通过实现自定义的getattr方法来实现一些功能是一个不错的方式,因为它不会像getattribute方法每次都会调用可能会影响一些正常情况下的属性访问:

class Test(object):
def __init__(self, p):
self.p = p def __getattr__(self, item):
return 'default' t = Test('p1')
print t.p
print t.p2 >>> p1
>>> default

2. 自定义getattribute的时候防止无限递归

因为getattribute在访问属性的时候一直会被调用,自定义的getattribute方法里面同时需要返回相应的属性,通过self.__dict__取值会继续向下调用getattribute,造成循环调用:

class AboutAttr(object):
def __init__(self, name):
self.name = name def __getattribute__(self, item):
try:
return super(AboutAttr, self).__getattribute__(item)
except KeyError:
return 'default'

这里通过调用绑定的super对象来获取队形的属性,对新式类来说其实和object.__getattribute__(self, item)一样的道理:

  • 默认情况下自定义的类会从object继承getattribute方法,对于属性的查找是完全能用的
  • getattribute的实现感觉还是挺抽象化的,只需要绑定相应的实例对象和要查找的属性名称就行

3.同时覆盖掉getattribute和getattr的时候,在getattribute中需要模仿原本的行为抛出AttributeError或者手动调用getattr

class AboutAttr(object):
def __init__(self, name):
self.name = name def __getattribute__(self, item):
try:
return super(AboutAttr, self).__getattribute__(item)
except KeyError:
return 'default'
except AttributeError as ex:
print ex def __getattr__(self, item):
return 'default' at = AboutAttr('test')
print at.name
print at.not_exised >>>test
>>>'AboutAttr' object has no attribute 'not_exised'
>>>None

上面例子里面的getattr方法根本不会被调用,因为原本的AttributeError被我们自行处理并未抛出,也没有手动调用getattr,所以访问not_existed的结果是None而不是default.

  

  

  

  

Python __getattribute__ vs __getattr__的更多相关文章

  1. python __getattribute__、__getattr__、__setattr__详解

    __getattribute__ 官方文档中描述如下: 该方法可以拦截对对象属性的所有访问企图,当属性被访问时,自动调用该方法(只适用于新式类).因此常用于实现一些访问某属性时执行一段代码的特性. 需 ...

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

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

  3. day26 Python __getattribute__

    __getattr__#不存在的属性访问,触发__getattr__ class Foo: def __init__(self,x): self.x=x def __getattr__(self, i ...

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

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

  5. Python中__get__, __getattr__, __getattribute__的区别及延迟初始化

    本节知识点 1.__get__, __getattr__, __getattribute__的区别 2.__getattr__巧妙应用 3.延迟初始化(lazy property) 1.__get__ ...

  6. Python魔法方法__getattr__和__getattribute__详解

    在Python中有这两个魔法方法容易让人混淆:__getattr__和getattribute.通常我们会定义__getattr__而从来不会定义getattribute,下面我们来看看这两个的区别. ...

  7. python __setattr__、__getattr__、__getattribute__全面详解

    一.属性引用函数 hasattr(obj,name[,default])getattr(obj,name)setattr(obj,name,value)delattr(obj,name) 二.属性引用 ...

  8. python中__get__,__getattr__,__getattribute__的区别

    __get__,__getattr__和__getattribute都是访问属性的方法,但不太相同. object.__getattr__(self, name) 当一般位置找不到attribute的 ...

  9. Python的__getattribute__ vs __getattr__的妙用

    这里的属性即包括属性变量,也包括属性方法.即类的变量和方法. 当访问某个实例属性时, getattribute会被无条件调用,如未实现自己的getattr方法,会抛出AttributeError提示找 ...

随机推荐

  1. Updated: Database Partitioning with EBS Whitepaper

    Partitioning allows a single database table and its associated indexes to be broken into smaller com ...

  2. git clone 时显示Filename too long的解决办法

    在git bash中,运行下列命令: git config --global core.longpaths true 就可以解决该问题. --global是该参数的使用范围,如果只想对本版本库设置该参 ...

  3. New Concept English three (37)

    28 words/minute 44 typing errors We have learnt to expect that trains will be punctual. After years ...

  4. “一键”知道自己的IP地址和网络供应商

    打开浏览器,然后在地址栏里面输入“www.baidu.com” 进入百度主页以后,在搜索框内输入 “ip”,然后回车就可以了

  5. postgresql recovery.conf改变需要重启吗

    之前在研究pgpoll时,发现trigger_file参数指定的文件存在后,会自动将standby节点提升为可写节点.不需要手动执行pg_ctl promote,但是这个时间一般有延迟,因为进程会定期 ...

  6. socket INADDR_ANY

    linux下的socket INADDR_ANY表示的是一个服务器上所有的网卡(服务器可能不止一个网卡)多个本地ip地址都进行绑定端口号,进行侦听. 不光是多个网卡的问题. 见如下server lis ...

  7. xhtml html

    xhtml是用xml语言重写了html,相比html更规范了, XHTML是HTML像XML的一个过渡语言,它比HTML严谨性会高点,然后基本语言都还是沿用的HTML的标签,只不过废除了部分表现层的标 ...

  8. NTP服务器和国内可用的NTP地址

    NTP 是什么?   NTP 是网络时间协议(Network Time Protocol),它用来同步网络设备[如计算机.手机]的时间的协议. NTP 实现什么目的?   目的很简单,就是为了提供准确 ...

  9. 背景色与WM_ERASEBKGND

    1.背景模式 SetBkMode(TRANSPARENT/OPACITY) 用来反应文字,图形与窗口背景交互混合模式.透明则表示文字背景与窗口背景之间透明,互不干扰. 2.背景颜色 SetBkColo ...

  10. CS与BS区别

    简介:CS即Client/Server(客户机/服务器)结构,C/S结构在技术上很成熟,它的主要特点是交互性强.具有安全的存取模式.网络通信量低.响应速度快.利于处理大量数据.但是该结构的程序是针对性 ...