1.__getattr__ 方法的作用:当调用不存在的属性,就会调用__getattr__()方法:
当一般位置找不到attribute的时候,会调用getattr,返回一个值或AttributeError异常。
class abc(): def __getattr__(self, item): print itemabc().test
那么它能干什么呢?
sdk的链式调用就可以用它来实现
结果:
class Dir(object): def __init__(self, path=""): self.__path = path def __getattr__(self, path): print "path:", path print 1 print "self.__path:",self.__path # :renfanzi return Dir("%s/%s" %(self.__path, path)) def __call__(self, user): # print 2 # print user return self.__getattr__(":" + user) def __str__(self): return self.__path# print Dir("GET ").users('renfanzi').repos# print Dir("GET ").usersasdfasd
详情链接:https://www.douban.com/note/304331534/