网络编程
位置:首页>> 网络编程>> Python编程>> Python的函数嵌套的使用方法

Python的函数嵌套的使用方法

  发布时间:2022-03-23 10:28:54 

标签:Python,函数嵌套

例子:


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()

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com