python 函式物件
阿新 • • 發佈:2020-08-10
函式是第一類物件:指的是函式可以當做資料傳遞
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