Discuss / Python / 习题

习题

Topic source
# -*- coding:utf-8 -*-
class Chain(object):

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

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

    #只需添加如下的 __call__() 函数即可
    def __call__(self,path):
        return Chain('%s/%s' % (self._path, path))

    def __str__(self):
        return self._path

    __repr__ = __str__


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

myth8023lj

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

为什么不能像repr = str 使call = getattr

安迪博德

#3 Created at ... [Delete] [Delete and Lock User]
Chain().users('michael').repos

为什么__call__竟然可以作用于类实例的一个不存在的方法?


  • 1

Reply