gpt4 book ai didi

python - 将方法参数传递给其父类构造函数(Flask -- ModelView.as_view())

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:10 27 4
gpt4 key购买 nike

这更像是一个一般的 Python 问题,而不是 Flask 问题。

这段代码来自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 方面的知识,以便更好地理解正在发生的事情。

谢谢

最佳答案

这一行是关键:

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

它采用传递给 as_view 的参数,并使用它们创建带有这些参数的 view 实例。

关于python - 将方法参数传递给其父类构造函数(Flask -- ModelView.as_view()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15280238/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com