函数的对象

函数的对象

  • 函数是第一类对象,即函数可以被当作数据处理。
def func():
    pass

print(func)  # 打印函数的内存地址。
             # print(func()) 打印的是函数的返回值。
# <function func at 0x0000006954051EA0>

函数对象的四大功能

1:引用

def index():
    print('from index')

index
f = index  # 可以拿一个变量名去接收函数名。
print(index)
print(f)
# <function index at 0x000000378C821EA0>
# <function index at 0x000000378C821EA0>

2:当作参数传给一个函数

def func():
    print('from func')

def index(type):  # 这里的 type 就是一个变量名,只用来接收值的。
    print('from index')
    type()
index(func)  # 将函数当作参数传给另一个函数。
# from index
# from func

3:可以当作一个函数的返回值

def func():
    print('from func')

def index():
    print('from index')
    return func  # 将函数当作返回值,返回给 index() 调用阶段。
res = index()  # 将其赋值给 res , res 就是 func。
res()  # res() 就等同于 func() 开始调用 func 的函数。 
# from index
# from func

4:可以当作容器类型

def register():
    print('from register')


def login():
    print('from login')


def shopping():
    print('from shopping')


l = [register,login,shopping]
l[0]()  # 通过索引取出 register() 调用函数
l[1]()
l[2]()
# from register
# from login
# from shopping

猜你喜欢

转载自www.cnblogs.com/jincoco/p/11164120.html