当前位置 博文首页 > Python的函数嵌套的使用方法

    Python的函数嵌套的使用方法

    作者:admin 时间:2021-06-19 19:30

    例子:

    复制代码 代码如下:

    def re_escape(fn):
        def arg_escaped(this, *args):
            t = [isinstance(a, VerEx) and a.s or re.escape(str(a)) for a in args]
            return fn(this, *t)
        return arg_escaped

    函数嵌套
    python允许在定义函数的时候,其函数体内又包含另外一个函数的完整定义,这就是我们通常所说的嵌套定义。为什么?因为函数是用def语句定义的,凡是其他语句可以出现的地方,def语句同样可以出现。
    像这样定义在其他函数内的函数叫做内部函数,内部函数所在的函数叫做外部函数。当然,我们可以多层嵌套,这样的话,除了最外层和最内层的函数之外,其它函数既是外部函数又是内部函数。

    使用方法

    复制代码 代码如下:

    spam = 99
    def tester():
        def nested():
            global spam
            print('current=',spam)
            spam += 1
        return nested

    #注意:打印 print 那行的代码调用是tester()()
    #而不是tester().nested()

    js
    下一篇:没有了