2013-03-07 84 views
2

這是一個比Flask問題更普遍的Python問題。將方法參數傳遞給它的父類構造函數(Flask - ModelView.as_view())

這段代碼來自https://github.com/mitsuhiko/flask/blob/master/flask/views.py#L18

@classmethod 
def as_view(cls, name, *class_args, **class_kwargs): 
    """Converts the class into an actual view function that can be used 
    with the routing system. Internally this generates a function on the 
    fly which will instantiate the :class:`View` on each request and call 
    the :meth:`dispatch_request` method on it. 

    The arguments passed to :meth:`as_view` are forwarded to the 
    constructor of the class. 
    """ 
    def view(*args, **kwargs): 
     self = view.view_class(*class_args, **class_kwargs) 
     return self.dispatch_request(*args, **kwargs) 

    if cls.decorators: 
     view.__name__ = name 
     view.__module__ = cls.__module__ 
     for decorator in cls.decorators: 
      view = decorator(view) 

    # we attach the view class to the view function for two reasons: 
    # first of all it allows us to easily figure out what class-based 
    # view this thing came from, secondly it's also used for instantiating 
    # the view class so you can actually replace it with something else 
    # for testing purposes and debugging. 
    view.view_class = cls 
    view.__name__ = name 
    view.__doc__ = cls.__doc__ 
    view.__module__ = cls.__module__ 
    view.methods = cls.methods 
    return view 

有人可以給我解釋一下這個as_view()功能到底如何,因爲它說,它的方法評論它的參數轉發到View類的構造函數?

如果不是一個直接的解釋,也許是在正確的方向上推進具體什麼我需要學習Python的明智,以更好地瞭解發生了什麼事情。

感謝

回答

3

這條線路是最關鍵的一步:

self = view.view_class(*class_args, **class_kwargs) 

它正在傳遞到as_view的參數和使用他們創造的view使用這些參數的實例。

+0

感謝Daniel,儘管我不太清楚當'view'是一個函數時我們可以如何調用(例如)'view.view_class = cls'。我們不應該傳遞params,或者至少使用像view()'.view_class這樣的括號嗎? – 2013-03-07 20:58:26

+0

函數就像Python中的所有其他對象一樣,並且它們可以附加屬性。這是在函數定義之後完成的:'view.view_class = cls'。換句話說,view函數被賦予了一個屬性'view_class',它是包含類,因此調用它將實例化該類。 – 2013-03-07 21:00:07

+0

所以(在這種情況下),只要我們調用view.'它將執行該方法並分配任何'self.dispatch_request(* args,** kwargs)'返回,然後我們訪問'view_class'? – 2013-03-07 21:05:32

相關問題