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

2015-07-17 20:26:24 +08:00
 sldaniel

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

3794 次点击
所在节点    Python
9 条回复
jyjmrlk
2015-07-17 20:56:12 +08:00
有点像递归啦。

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
2015-07-17 21:06:03 +08:00
@jyjmrlk 难道意思是说把'.status'、'.user'、'.timeline'、'.list'当成了四个实例依次调用,然后这四后实例都没有,所以每次都运行了一下'%s/%s'?
我一开始理解的是‘status.user.timeline.list’当成一个实例输入输出,所以__getattr__只会调用一次。
linnchord
2015-07-17 21:23:14 +08:00
相当于

Chain().__getattr__('status').__getattr__('user').__getattr__('timeline').__getattr__('list')
sldaniel
2015-07-17 22:33:02 +08:00
@linnchord 噢,这么写就很清楚了。。谢谢哈
sivacohan
2015-07-18 13:22:59 +08:00
这个玩法每次都会生成一个Chain的实例。
从逻辑上来讲效率应该很低吧。
实际使用中强烈建议不要这么玩。如果一定要这么玩,请务必最好缓存。
sivacohan
2015-07-18 13:23:49 +08:00
@jyjmrlk 这玩意在js里面叫链式调用吧,理论基础是方法返回的是本身的对象。
sldaniel
2015-07-18 14:05:28 +08:00
@sivacohan 对,教程里就说是链式调用,不过是Python的,我才刚学,还没到考虑效率的地步,哈哈~
qqblog
2015-07-22 23:06:20 +08:00
怎么不找廖?
sldaniel
2015-07-23 09:33:41 +08:00
@qqblog 他下面的很多评论他都不回复的丫

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/206472

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX