在python中,函数名不单单是一个名称,还有其他的一些用法
目录
函数名的内存地址
在定义函数后,当系统运行到定义函数的位置是,他只会记录下当前函数的内存地址,是不会之间运行函数内部的代码的,直到运行到调用函数时,才会运行函数内部的代码,而这个函数的内存地址查看很简单,使用print函数输出函数名即可。
def content():
print('hello world')
print(content) #输出结果为<function content at 0x0000029AD9473E20>
输出结果中的一段数字就是该函数的内存地址,在查看地址时,函数名一定不要带括号,带了括号的函数名即表示调用函数了
函数的赋值
在python中,函数名也可以像变量一样,进行赋值操作
def content():
print('hello world')
a=content #将函数content赋值给a
a() #调用时也可以直接使用a加括号进行调用
函数名可以当做容器类的元素
在python中,既然函数名可以像变量一样进行赋值,那边也可以做为元素存储在列表等高级数据类型里的
def content1():
print('hello world')
def content2():
print('你好')
def content3():
print('世界')
list_content=[content1,content2,content3]
list_content[0]() #输出结果为hello world
进行调用时也可以通过索引加括号的方式。
函数名可以当作函数的参数
与正常传参一样,在传入时不要加括号,传入函数名即可,系统会先运行传入的函数中的内容,然后再运行外部函数的内容
def content1(fn): #形式参数为参数
print('hello world')
fn()
def content2():
print('你好')
content1(content2) #实际参数为函数传入
'''
hello world
你好
'''
函数可以作为函数的返回值
当函数这位另一个函数的返回值时,当函数1内部的代码多了后,使用函数作为返回值调用时,使用使代码更简洁
在全局中定义的函数
def content2():
print('你好')
def content1():
print('hello world')
return content2()
content1()
'''
输出内容为
hello world
你好
'''
嵌套函数时:
def content2():
print('你好')
def content1():
print('hello world')
def content2():
print('你好')
return content2()
content1()
'''
hello world
你好
'''