Discuss / Python / __getattr__习题

__getattr__习题

Topic source

4Neutrino

#1 Created at ... [Delete] [Delete and Lock User]
class Chain(object):

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

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

    def users(self, usr):
        return Chain('%s/users/%s' % (self._path, usr))

    def __str__(self):
        return self._path

    __repr__ = __str__

c = Chain().users('michael').repos
print(c)

4Neutrino

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

看了讨论,确实有BUG,修改如下:

class Chain(object):

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

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

    def __call__(self, arg):
        return self.__getattr__(arg)

    def __str__(self):
        return self._path

    __repr__ = __str__

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

  • 1

Reply