Discuss / Python / 学到了定制类的作用

学到了定制类的作用

Topic source

蝎尾蛇嚴

#1 Created at ... [Delete] [Delete and Lock User]

了解了定制类的作用和意义,具体的代码和应用,需要的时候再回来看

蝎尾蛇嚴

#2 Created at ... [Delete] [Delete and Lock User]

问题:写出一个链式调用,实现Chain().users('michael').repos 的输出结果是/users/michael/repos

答案:

class Chain(object):

    def __init__(self, path=''):

        self._path = path

    def __getattr__(self, attr):

        return Chain('%s/%s' % (self._path, attr))

    def __call__(self, name):

        return Chain('%s/%s' % (self._path, name))

    def __str__(self):

        return self._path

    __repr__ = __str__


  • 1

Reply