现在很多网站都搞REST API,比如新浪微博、豆瓣啥的,调用API的URL类似:
- http://api.server/user/friends
- http://api.server/user/timeline/list
- http://api.server/users/:user/repos
如果要写SDK,给每个URL对应的API都写一个方法,那得累死,而且,API一旦改动,SDK也要改
链式调用的方式实现
View Code1 class Chain(object): 2 def __init__(self, path=''): 3 self.__path = path 4 5 def __getattr__(self, item): 6 return Chain('%s/%s' % (self.__path, item)) 7 8 def __call__(self, *args, **kwargs): 9 return Chain('%s/%s' % (self.__path, *args)) 10 11 def __str__(self): 12 prefix = 'http://api.server' 13 return prefix + self.__path 14 15 __repr__ = __str__ 16 17 print(Chain().user.friends) 18 print(Chain().user.timeline.list) 19 print(Chain().users('zhangsan').repos)