Discuss / Python / 检测楼下'__getattr__' 和 ‘__call__’ 如何走的方法

检测楼下'__getattr__' 和 ‘__call__’ 如何走的方法

Topic source

Zflyee

#1 Created at ... [Delete] [Delete and Lock User]
class Chain(object):
    def __init__(self, path = ''):
        print('__init__',path)
        self._path = path
    def __getattr__(self, path):
        print('__getattr__',path)
        return Chain('%s/%s' % (self._path, path))
    def __call__(self, path):
        print('__call__',path)
        return Chain('%s/%s' % (self._path, path))
    def __str__(self):
        return self._path
    __repr__ = __str__

运行结果:

>>> print(Chain().a.b.user("ChenTian").c.d)
__init__ 
__getattr__ a
__init__ /a
__getattr__ b
__init__ /a/b
__getattr__ user
__init__ /a/b/user
__call__ ChenTian
__init__ /a/b/user/ChenTian
__getattr__ c
__init__ /a/b/user/ChenTian/c
__getattr__ d
__init__ /a/b/user/ChenTian/c/d
/a/b/user/ChenTian/c/d

千羽王爵

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

非常感谢,一目了然!

great!


  • 1

Reply