Discuss / Python / __getattr__ 返回函数的例子这样写,可能会更好理解

__getattr__ 返回函数的例子这样写,可能会更好理解

Topic source

大晨紫Zzz

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

class Chain(object):

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

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

def _user(self,item):
    return Chain('%s/%s' % (self._path, item))


def __str__(self):
    return self._path

__repr__ = __str__

print(Chain().users('abc').repos)


  • 1

Reply