Discuss / Python / 代码解析

代码解析

Topic source
class Chain(object):
    def __init__(self, path=''):
       self.__path = path

    def __getattr__(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__

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

1.a = Chain(),即进行实例化, 此时self.__path = ''

2.b = a.users,即对实例中名为users的属性进行访问,由于没有users属性,则尝试从__getattr__获得属性,传入了参数users,返回Chain('/users').此时再一次进行实例化,self.__path = /users;

3.b.('michael')是对实例进行调用,运行的是__call__函数,同时传入参数'michael',返回Chain(/users/micheal).此时再一次进行实例化,self.__path = /users/michael

4.c = b.(michael);则c.repos对实例进行属性访问,过程同第二步相同.最后self.__path = /users/michael/repo

5.print(c);运行__str__方法,打印出self.__path

我本居士

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

运行廖老师的代码,

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

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'Chain' object is not callable

原来少了下边的调用函数

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

感谢大神


  • 1

Reply