V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
sldaniel
V2EX  ›  Python

看廖雪峰 python 的教程,有一段关于__getattr__()的代码看不懂,请教大神们。

  •  
  •   sldaniel · 2015-07-17 20:26:24 +08:00 · 3716 次点击
    这是一个创建于 3211 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://gist.github.com/danfate/316f1735fb577eca1191
    上面的是代码
    输入‘Chain().status.user.timeline.list’的话,
    输出是'/status/user/timeline/list'这个.
    我不理解的是‘return Chain('%s/%s' % (self._path, path))’这个怎么会返回上面的结果的?新手自学的,很多地方都看的稀里糊涂。。

    9 条回复    2015-07-23 09:33:41 +08:00
    jyjmrlk
        1
    jyjmrlk  
       2015-07-17 20:56:12 +08:00   ❤️ 1
    有点像递归啦。

    object.__getattr__(self, name)
    Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

    找不到 attr 就会调用 __getattr__ ,__getattr__ 继续返回 Chain 的实例,但是又没找到,于是在调用 __getattr__, 如此反复。
    sldaniel
        2
    sldaniel  
    OP
       2015-07-17 21:06:03 +08:00
    @jyjmrlk 难道意思是说把'.status'、'.user'、'.timeline'、'.list'当成了四个实例依次调用,然后这四后实例都没有,所以每次都运行了一下'%s/%s'?
    我一开始理解的是‘status.user.timeline.list’当成一个实例输入输出,所以__getattr__只会调用一次。
    linnchord
        3
    linnchord  
       2015-07-17 21:23:14 +08:00   ❤️ 1
    相当于

    Chain().__getattr__('status').__getattr__('user').__getattr__('timeline').__getattr__('list')
    sldaniel
        4
    sldaniel  
    OP
       2015-07-17 22:33:02 +08:00
    @linnchord 噢,这么写就很清楚了。。谢谢哈
    sivacohan
        5
    sivacohan  
       2015-07-18 13:22:59 +08:00 via Android   ❤️ 1
    这个玩法每次都会生成一个Chain的实例。
    从逻辑上来讲效率应该很低吧。
    实际使用中强烈建议不要这么玩。如果一定要这么玩,请务必最好缓存。
    sivacohan
        6
    sivacohan  
       2015-07-18 13:23:49 +08:00 via Android
    @jyjmrlk 这玩意在js里面叫链式调用吧,理论基础是方法返回的是本身的对象。
    sldaniel
        7
    sldaniel  
    OP
       2015-07-18 14:05:28 +08:00
    @sivacohan 对,教程里就说是链式调用,不过是Python的,我才刚学,还没到考虑效率的地步,哈哈~
    qqblog
        8
    qqblog  
       2015-07-22 23:06:20 +08:00
    怎么不找廖?
    sldaniel
        9
    sldaniel  
    OP
       2015-07-23 09:33:41 +08:00
    @qqblog 他下面的很多评论他都不回复的丫
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   848 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:41 · PVG 06:41 · LAX 15:41 · JFK 18:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.