Python的函數嵌套的使用方法

來源:互聯網
上載者:User
例子:
複製代碼 代碼如下:


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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.