# 說說 Python 函數對象的本質

Python 函數對象本質上是 function 類的實例1

## 1 從示例說起

def factorial(n):
'''return n!'''
return 1 if n < 2 else n * factorial(n - 1)

r = factorial(42)
logging.info('r -> %s', r)
logging.info('__doc__ -> %s', factorial.__doc__)
logging.info('type(factorial)  -> %s', type(factorial))

INFO - r -> 1405006117752879898543142606244511569936384000000000
INFO - __doc__ -> return n!
INFO - type(factorial) -> <class 'function'>

## 2 help 函數

python 中還有一個 help 函數，它可以接受一個自定義函數作爲入參，然後輸出該函數的說明文檔。形如：

help(factorial)

Help on function factorial in module __main__:

factorial(n)
return n!

## 3 函數別名與函數傳參

f = factorial
logging.info('f -> %s', f)
logging.info('f(5) -> %s', f(5))

r = map(factorial, range(11))
logging.info('r -> %s', r)

r = list(map(f, range(11)))
logging.info('r -> %s', r)

INFO - f -> <function factorial at 0x0000027278917798>
INFO - f(5) -> 120
INFO - r -> <map object at 0x000002727893F588>
INFO - r -> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

【1】Luciano Ramalho (作者)，安道，吳珂 (譯者)．流暢的Python[M]．人民郵電出版社，2017:239-240.
【2】Python map() 函數.
【3】Python range() 函數用法.