PythonStudy——函数对象的案例
# part1
# 加法运算
def add(n1, n2): return n1 + n2 def low(n1, n2): return n1 - n2
# 四则运算
def computed(n1, n2, func): # if cmd == 'add': # return add(n1, n2) # elif cmd == 'low': # return n1 - n2 return func(n1, n2) r1 = computed(10, 20, add) print(r1) r2 = computed(10, 20, low) print(r2)
# part2
def add(n1, n2): return n1 + n2 def low(n1, n2): return n1 - n2 def computed(n1, n2, func): return func(n1, n2)
# 测试 cmd = input('cmd: ') # 只能等于字符串add、low => 什么方式可以将字符串add、low对应上函数 fn = None if cmd == 'add': fn = add elif cmd == 'low': fn = low computed(10, 20, fn)
# 直接输入cmd 也及时传入了一个函数对象
# 测试 fn_map = { 'add': add, 'low': low } if cmd in fn_map: # 作为容器的成员可以简化判断逻辑 fn = fn_map[cmd] res = computed(10, 20, fn) print(res) else: print('该运算暂不支持')
# part 3
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, func): return func(n1, n2) fn_map = { 'add': add, 'low': low, 'jump': jump } def get_fn(cmd): f = add # 默认为add函数 if cmd in fn_map: f = fn_map[cmd] # 如果指令正确就返回对应的函数,如果不正确,就是采用默认的函数 return f
while True: cmd = input('cmd: ') if cmd == 'q': break if cmd in fn_map: fn = fn_map[cmd] # 通过指令找函数 res = computed(10, 20, fn) print(res) else: print('该运算暂不支持')