一:函數調用順序:其餘高級語言相似,Python 不容許在函數未聲明以前,對其進行引用或者調用python
def bar(): print('in the bar') def foo(): print('in the foo') bar() foo()
錯誤示範app
def foo(): print('in the foo') bar() foo()
def bar():
print('in the bar')
E:\python\python.exe E:/pyproject/1/裝飾器.py in the foo Traceback (most recent call last): File "E:/pyproject/1/裝飾器.py", line 9, in <module> foo() File "E:/pyproject/1/裝飾器.py", line 7, in foo bar() NameError: name 'bar' is not defined
二:高階函數函數
知足下列條件之一就可成函數爲高階函數spa
一、某一函數當作參數傳入另外一個函數中code
二、函數的返回值包含n個函數,n>0blog
def bar(): print ('in the bar') def foo(func): res=func() return res foo(bar) #等同於bar=foo(bar)而後bar() in the bar
三:內嵌函數和變量做用域:作用域
定義:在一個函數體內建立另一個函數,這種函數就叫內嵌函數(基於python支持靜態嵌套域)ast
函數嵌套示範:class
def foo(): def bar(): print('in the bar') bar() foo() in the bar
局部做用域和全局做用域的訪問順序test
x=0 def grandpa(): x=1 print(x) def dad(): x=2 print(x) def son(): x=3 print (x) son() dad() grandpa()
局部變量修改對全局變量的影響
y = 10 def test(): y = 2 print(y) test() print(y) 2 10
四:裝飾器
裝飾器:嵌套函數+高階函數
調用方式:在原函數前面@裝飾器函數名
示例:原函數test,調用方式test(),在不改變原函數以及不改變原函數調用的狀況下新增計時功能。
import time def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) stop = time.time() print('run time is %s ' % (stop - start)) return wrapper @decorator #test=decorator(test)-->test=wrapper-->test()=wrappper() def test(list): for i in list: time.sleep(0.1) print('-' * 20, i) test(range(10)) E:\python\python.exe E:/pyproject/1/裝飾器.py -------------------- 0 -------------------- 1 -------------------- 2 -------------------- 3 -------------------- 4 -------------------- 5 -------------------- 6 -------------------- 7 -------------------- 8 -------------------- 9 run time is 1.0073368549346924