Discuss / Python / 实现restful,可以借助__getattr__ 和 __call__;python的魔法方法太多太强大了

实现restful,可以借助__getattr__ 和 __call__;python的魔法方法太多太强大了

Topic source

B O O M!

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

class Chain(object):

    def __init__(self, path ='') -> None:

        self._path = path

    def __getattr__(self, __name: str) -> Any:

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

    def __call__(self, *args: Any, **kwds: Any) -> Any:

        if not len(args):

            return

        for arg in args:

            if (not arg is None):

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

    def __str__(self) -> str:

        return self._path

    __repr__ = __str__

print(Chain().users('michael').repos, Chain().users('michael').repos.id('123').view)


  • 1

Reply