在 Python 中,函数是一等对象。编程语言理论家把“一等对象”定义为满
足下述条件的程序实体:
对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
看看下面两个示例:
# 案例1
In [20]: def factorial(n):
...: """return n!"""
...: return 1 if n<2 else n*factorial(n-1)
...:
In [21]: factorial(12)
Out[21]: 479001600
# 获取对象属性
In [22]: factorial.__doc__
Out[22]: ‘return n!‘
# function类
In [23]: type(factorial)
Out[23]: function
# 案例2
In [24]: fact = factorial
In [25]: fact
Out[25]: <function __main__.factorial(n)>
In [26]: fact(5)
Out[26]: 120
In [27]: map(factorial, range(10))
Out[27]: <map at 0x7f9c08954e80>
In [28]: list(map(factorial, range(10)))
Out[28]: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
上面两个案例,表现出对象的行为.
原文:https://www.cnblogs.com/zyl007/p/15171731.html