python 函数对象

函数是第一类对象:指的是函数可以当做数据传递
1、可以被引用 x=1, y=1
def func(x, y):
print(x, y)

f=func
f(1,2)
输出结果:1 2

2、可以当做函数的参数传入
def func():
print("hello world!")

def bar(x):
print(x)

bar(func)
输出结果:<function func at 0x000001FF4AFCC268>(输出的是函数func的内存地址)

def func():
print("hello world!")

def bar(x):
func()

bar(func)
输出结果:hello world!

3、可以当做函数的返回值
def func():
print("hello world!")

def bar(x):
return func 返回的是func的内存地址

x = bar(func) 得到的是func的内存地址
x() 得到的是func的值
输出结果:hello world!

4、可以当做容器类型的元素
def foo():
print("hello world!")

def bar():
return foo

l = [foo, bar]
print(l)
输出结果:[<function foo at 0x0000021B0265C268>, <function bar at 0x0000021B02803840>]

def put():
print("put")

def ls():
print('ls')

def get():
print('get')

func_dict={
'get': get,
'put': put,
'ls': ls
}
cmd = input('>>:').strip()
if cmd in func_dict:
func_dict[cmd]()
输出结果:>>:get
     get








posted @ 2020-08-10 19:50  冰箱喵  阅读(305)  评论(0编辑  收藏  举报