可以再函數內再定義函數,將演算組成更小的組織重複利用
def function1():
# outer function
print ("Hello from outer function")
def function2():
# inner function
print ("Hello from inner function")
function2()
function1()
為何要用區域函數:
封裝
closure
可創建一個短小的匿名函數,出於語法限制,只能有一個單獨表達式
#%% Lambda Expressions
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
Lambda 函數的另一個功能,可以當作一個小函數物件 (function object) 傳入其他函數引數built-in function 很常使用 lambda 來當作運算條件,填入key 中
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair:pair[1])
pairs
students = [ ('Che', 10), ('Yo', 20), ('HowHow', 30)]
max(students,key=lambda i: i[1])
Documentation strings
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
print(my_function.__doc__)
型別提示
def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs
f('spam')
f.__annotations__
& https://docs.python.org/3.7/tutorial/controlflow.html#defining-functions