推荐学习书目
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
ApIEfuse
V2EX  ›  Python

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

  •  
  •   ApIEfuse · Jul 17, 2015 · 4400 views
    This topic created in 3964 days ago, the information mentioned may be changed or developed.

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

    9 replies    2015-07-23 09:33:41 +08:00
    yuanji
        1
    yuanji  
       Jul 17, 2015   ❤️ 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__, 如此反复。
    ApIEfuse
        2
    ApIEfuse  
    OP
       Jul 17, 2015
    @jyjmrlk 难道意思是说把'.status'、'.user'、'.timeline'、'.list'当成了四个实例依次调用,然后这四后实例都没有,所以每次都运行了一下'%s/%s'?
    我一开始理解的是‘status.user.timeline.list’当成一个实例输入输出,所以__getattr__只会调用一次。
    linnchord
        3
    linnchord  
       Jul 17, 2015   ❤️ 1
    相当于

    Chain().__getattr__('status').__getattr__('user').__getattr__('timeline').__getattr__('list')
    ApIEfuse
        4
    ApIEfuse  
    OP
       Jul 17, 2015
    @linnchord 噢,这么写就很清楚了。。谢谢哈
    sivacohan
        5
    sivacohan  
    PRO
       Jul 18, 2015 via Android   ❤️ 1
    这个玩法每次都会生成一个Chain的实例。
    从逻辑上来讲效率应该很低吧。
    实际使用中强烈建议不要这么玩。如果一定要这么玩,请务必最好缓存。
    sivacohan
        6
    sivacohan  
    PRO
       Jul 18, 2015 via Android
    @jyjmrlk 这玩意在js里面叫链式调用吧,理论基础是方法返回的是本身的对象。
    ApIEfuse
        7
    ApIEfuse  
    OP
       Jul 18, 2015
    @sivacohan 对,教程里就说是链式调用,不过是Python的,我才刚学,还没到考虑效率的地步,哈哈~
    qqblog
        8
    qqblog  
       Jul 22, 2015
    怎么不找廖?
    ApIEfuse
        9
    ApIEfuse  
    OP
       Jul 23, 2015
    @qqblog 他下面的很多评论他都不回复的丫
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5825 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 06:39 · PVG 14:39 · LAX 23:39 · JFK 02:39
    ♥ Do have faith in what you're doing.