2013-03-07 79 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

相关问题