double lambda-内部函数-* args ** kwargs太复杂

时间:2019-01-10 00:50:35

标签: python-3.x lambda arguments

此应用正常运行,没有错误,我只想了解这部分代码。 请查看以下代码:

# *args any number of non-keywords params
# *kwargs any number of keywords params
def stack(*args):
"""
Builds a stack of apps. Each parameter represents a layer in the stack. Bottom first.

:param *args: List of pairs (class, kwargs) for each app in the stack.
:returns: stack of applications.

Sample usage:

    stack = app.stack(
        (
            session.SessionApp,
            dict(
                socket_klass = sb,
                username = user,
                password= password,
                we = user,
                you="NYSE",
                reset_seq_nums=True
            )
        ),
        (
            MyStrategyApp,
            dict(
                param1 = value1,
                param2 = value2
            )
        )
    )
"""

    # Generate constructor for up-most app
    # [-1] take last param
    klass, kwargs = args[-1]
    upper_klass = (
        lambda klass, kwargs: lambda lower_app: klass(lower_app=lower_app, **kwargs)
    )(klass, kwargs)

    def build_constructor(klass, kwargs, upper_klass):
        return lambda lower_app: klass(
            lower_app=lower_app, upper_klass=upper_klass, **kwargs
        )

    # Chain middle
    for klass, kwargs in reversed(args[1:-1]):
        upper_klass = build_constructor(klass, kwargs, upper_klass)

    # Generate base and return
    klass, kwargs = args[0]
    return klass(upper_klass=upper_klass, **kwargs)

我不明白这部分代码。我迷失了电话和退货

upper_klass = (
    lambda klass, kwargs: 
        lambda lower_app:
            klass(lower_app=lower_app,**kwargs))(klass, kwargs)

我需要一点帮助。预先感谢!

1 个答案:

答案 0 :(得分:0)

此:

upper_klass = (
    lambda klass, kwargs: 
        lambda lower_app:
            # this lambda should return a callable function
            # meaning the function call below should return another callable function
            klass(lower_app=lower_app,**kwargs)
        # end lambda
    # VVV this VVV calls the function returned by lower_app
    )(klass, kwargs)

与此相同:

def upper_klass(klass, **kwargs):
    klass(lower_app = lower_app, **kwargs)