Discuss / Python / 思考题:老师写在__call__前面,那么这题的写法这样比较好吧

思考题:老师写在__call__前面,那么这题的写法这样比较好吧

Topic source

Gin阿金

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

class Chain(object):

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

def users(self, name = ''):
    return Chain('users/%s' %name)

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

def __str__(self):
    return self._path

__repr__ = __str__

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

users/michael/repos

是不是还可以这样: class Chain(object):

def __init__(self, path=""):
    self.__path = path

def __getattr__(self, path):
       if path == 'users':
           self.__path = "%s/%s" % (self.__path, path)
           return lambda path: Chain("%s/%s" % (self.__path, path))
   return Chain("%s/%s" % (self.__path, path))

def __str__(self):
       return self.__path

__repr__ = __str___

if name=='main': print(Chain().users('mechael').repos)

我刚开始也这样写,但后来发现没有可延续性。

如果变成另外一个函数,譬如修改成

Chain().user('michael').repos

或者再增加一个函数

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

就会运行错误。


  • 1

Reply