# part1
owen_a = 10
# owen_a存放10的地址,所以也是对象,普通的整型对象
# 函数对象:存放函数地址的变量就叫函数对象,就是函数名
def fn():
print(1)
print(2)
print(3)
return 1
print(fn)
# 1.函数对象():拿到函数地址并执行 - 函数的调用
# 2.函数调用一定会得到一个结果 - 函数的返回值 - 函数值: res=fn() == 函数调用后res=1
res = fn()
print(res)
res = 1
print(res)
print('------------------------')
# part2
# 应用场景:
# 1 可以直接被引用
# 2 可以当作函数参数传递
# 3 可以作为函数的返回值
# 4 可以作为容器类型的元素
def fn2():
print('fn2 run')
# fn2()
aaa = fn2 # 直接赋值
# aaa()
def fn22(fn): # fn = aaa = fn2 # 作为参数
fn()
fn22(aaa)
def fn222():
# return fn2()
return fn2 # 作为返回值
res = fn222() # res = fn2() = None | res = fn2 = 函数对象
print(res())
ls = [fn2, 10, 20] # 作为容器对象的成员
print(ls[1])
print(ls[0]())
# 案例:
def add(n1, n2):
return n1 + n2
def low(n1, n2):
return n1 - n2
def jump(n1, n2):
return n1 * n2
def computed(n1, n2, fn):
res = fn(n1, n2)
return res
method_map = {
'1': add,
'2': low,
'3': jump
}
def get_method(cmd):
if cmd in method_map:
return method_map[cmd]
return add
while True:
cmd = input('cmd: ')
res = 0
# if cmd in method_map:
# # res = method_map[cmd](10, 20)
# fn = get_method(cmd)
# res = fn(10, 20)
res = get_method(cmd)(10, 20)
print(res)
# while True:
# cmd = input('cmd: ')
# res = 0
# if cmd == '1':
# res = computed(10, 20, add)
# elif cmd == '2':
# res = computed(10, 20, low)
# elif cmd == '3':
# res = computed(10, 20, jump)
# print(res)