【问题标题】:How to get parameters of factory functions如何获取工厂函数的参数
【发布时间】:2019-08-23 04:23:55
【问题描述】:

假设我有 Python 3.5 中的代码

def factory(param):
    def f(num):
        print(param*num)
    return f

fun = factory('a')
# how do I know, that fun was created with param='a'?
fun(3)

创建fun 后如何检查param 值?

【问题讨论】:

    标签: python python-3.x scope closures


    【解决方案1】:

    闭包变量位于the __closure__ attribute of the function。您可以直接查看,但最简单的方法可能是use inspect.getclosurevars 为您完成繁重的工作:

    import inspect
    
    def factory(param):
        def f(num):
            print(param*num)
        return f
    
    fun = factory('a')
    print(inspect.getclosurevars(fun))
    

    哪些输出(globalsbuiltins 的确切内容在实践中会有所不同):

    ClosureVars(nonlocals={'param': 'a'}, globals={}, builtins={'print': <built-in function print>}, unbound=set())
    

    或将其限制为在嵌套的非全局、非内置范围内直接查找的内容,访问 nonlocals 属性,这是一个 dict 将名称映射到关闭的值:

    >>> print(inspect.getclosurevars(fun).nonlocals)
    {'param': 'a'}
    

    【讨论】:

      【解决方案2】:

      您可以通过__closure__ 属性检查该函数的关闭:

      >>> fun.__closure__[0].cell_contents
      'a'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-30
        • 2015-06-04
        • 1970-01-01
        • 1970-01-01
        • 2021-02-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多