函数还能被返回,从而使事情变得更加简单。就像我们在 dict 中存储函数一样,我们还可以将函数作为控制语句,来决定适合的函数。例如:
正确代码
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def calculator(opcode):
if opcode == 1:
return add
elif opcode == 2:
return sub
else:
return mult
my_calc = calculator(2)
print(my_calc(5, 4))
my_calc = calculator(9)
print(my_calc(5, 4))
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def calculator(opcode):
if opcode == 1:
return add
elif opcode == 2:
return sub()
else:
return mult
my_calc = calculator(2)
print(my_calc(5, 4))
my_calc = calculator(9)
print(my_calc(5, 4))
问题是在函数作为返回值为什么不加括号
TypeError: sub() missing 2 required positional arguments: 'x' and 'y'
python中万物皆对象,函数也不例外,所以定义的函数是可以被赋值给另外一个变量的
函数的加了括号就是调用,当你返回加了括号的函数时就是在返回调用的函数,这不是本题的含义。