代码解析
Topic source运行廖老师的代码,
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
用户5307799436
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