Discuss / Python / 实现链式调用Chain().users('michael').repos

实现链式调用Chain().users('michael').repos

Topic source

青铜神裔

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

代码:

class Chain(object):

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

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

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

    def __str__(self):
        return self._path

    __repr__ = __str__

测试:Chain().users('michael').repos 结果:/michael/repos

解析:

  1. Chain()生成一个Chain类的实例,path='';
  2. .users调用该实例一个不存在的属性users,实质调用__getattr__(self,'users'),根据条件判断,返回原Chain实例,path依然为'';
  3. ('michael')直接对上一步生成的实例本身进行调用,传入参数为'michael',即调用__call__(self,'michael'),返回Chain实例,path='/michael';
  4. .repos调用实例不存在的属性repos,实质调用__getattr__(self,'repos'),返回一个Chain实例,path='/michael/repos';
  5. 此时等于直接输入一个变量,调用__repr__(self),若外加一个print函数,则调用__str__(self),输出结果

  • 1

Reply