聽說你不會python鏈式調用?快來看看吧

問題:

看幾個http的rest調用的例子:

  • /users/list
  • /user/{someone}/detail

用python如何實現:

  • Class.users.list生成/users/list
  • Class.users(someone).detail生成/user/{someone}/detail

原理

__getattr__方法

python定製類,可以實現__getattr__(self,*args, **kw)方法,當調用一個類的屬性且該屬性在類中未定義,會進入該方法,例子如下:

class Test(object):
    name = 'name1'
    
    def __getattr__(self, attr):
        if(attr == 'age'):
            return 11
        
test = Test()
print(test.name)
print(test.age)

該例子輸出:
name1 和 11

__call__方法

我們知道實例化一個class後,產生實例s,可以通過s.methodName()這種方式調用類中定義的方法。
在python中,可以通過實現__call__(self,*args,**kw)方法,直接調用實例,類似於s(),,此時s是一個callable對象,可以通過callable(s)進行判斷,輸出爲True。(python中的類爲啥開頭不是大寫呢)

此時對象和函數是一樣的(對象和函數可以看做一樣的麼?)

class Test(object):
    
    def __call__(self, something):
        print(something)
        
test = Test()
test("hello")

該例子輸出hello

實踐出真知,大力出奇跡

class Chain1(object):
    
    def __init__(self,fun=''):
        self._path = fun
    
    def __getattr__(self, path):
        return Chain1(self._path+'/'+path)
    
    def __call__(self, detail):
        return Chain1(self._path+'/'+detail)
    
    def __str__(self):
        return (self._path)
        
    __repr__=__str__
    
    def getPath(self):
        print(self._path)
    
if __name__ == '__main__':
    print(Chain1().users('xiaoming').hello)
    print(Chain1().users.list)
    '''
    /users/xiaoming/hello
    /users/list
    '''

才疏學淺,有不當之處請指正~,與君共勉

更多學習:
對象和函數可以看做一樣的麼?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章