python 定制类之动态属性实现链式调用

今天继续学习python,学到了定制类,用到了__getattr__和__call__以及__str__
class Chain(object):

    def __init__(self, path=''):
        self._path = path

    def __getattr__(self, path):
        return Chain('%s/%s' % (self._path, path))

    def __str__(self):
        return self._path

    def __call__(self, param):
        return Chain('%s/%s' % (self._path, param))

    __repr__ = __str__

这个链式用法可以做到,构建动态api地址使用,比如如下例子

url1 = Chain().users.test
print(url1)

url = Chain().users('mac').photo('testphoto').repos
print(url)

两个例子结果输出如下

/users/test
/users/mac/photo/testphoto/repos

相信不用多解释大家也能看到效果,这个确实比java的那个强大

0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x