函数对象与闭包

1. 函数的对象

# 函数对象就是函数名
函数名的使用有四种用法
# 1. 函数名可以当成变量名来使用
# def index():  # index它是属于全局的
#     print('index')
#
# """函数名就是函数的内存地址"""
# # print(globals())  # 'index': <function index at 0x00000123F32BE310> value值就是函数的内存地址
# # print(index)
# # index() # 直接调用函数
# a = index
# a()  # index()

# 2. 函数名也可以当成函数的实参
# def index():
#     print('from index')

# def func(func_name):
#     # func_name----->index
#     print('from func')
#     func_name() # 相当于是index()
#
#
# func(index)

# 3. 函数名也可以当成函数的返回值
# def index():
#     print('from index')
#
#
# def func():
#     print('from func')
#     # return index()  # None
#     return index
#
# res=func()  # res是函数的内存地址
# res()  # index()
# print(res)


# 4. 函数名也可以当成容器类型的元素
def index():
    print('from index')

2. 函数的嵌套调用

# 函数之间互相调用,函数里面调用函数
# 常用场景:
# 1. 定义一个函数,功能是比较两个数的大小
def my_max(a, b):
    if a > b:
        return a
    return b


# res = my_max(1, 10)
# print(res)

# 2. 定义一个函数,比较4个数的大小
def many_max(a, b, c, d):
    res = my_max(a, b)  # res是a和b中的最大的
    res1 = my_max(res, c)  # res1就是abc中的最大值
    res2 = my_max(res1, d)  # res2就是abcd中的最大值
    print(res2)
    return res2

3. 闭包函数

1. 什么是闭包函数?
	闭:闭就是函数内部定义函数,至少两层函数
    	def outer():
            def inner():
                pass
         
     包:内部的函数使用外部函数名称空间中的名字
  	'''只有同时满足以上两个条件才能称之为是闭包函数'''
# 闭包函数有什么用?使用场景?

'''闭包函数其实是给函数传参的第二种方式!'''
posted @ 2023-10-05 21:28  苙萨汗  阅读(15)  评论(0)    收藏  举报