问题的提出:我们知道可以通过定义类(class)的方法在一个函数内调用和访问另一个类内的函数或方法。那么如果不定义类,怎样用一个函数调直接用另一个函数?
1、嵌套:
def a():
def b():
pass
return b
func_b = a() # 获取函数b()的引用
func_b() # 调用函数b()
函数b()被定义在函数a()的内部,因此它的作用域仅限于a()函数内部,在a()函数外部无法直接访问和调用函数b()。将函数b()作为a()函数的返回值,这样在调用a()函数时可以得到函数b()的引用
demo:
def calculate(method, x, y):
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
if method == 'add':
return addition(x, y)
elif method == 'sub':
return subtraction(x, y)
elif method == 'mul':
return multiplication(x, y)
elif method == 'div':
return division(x, y)
num1 = calculate('add', 3, 2)
num2 = calculate('sub', 3, 2)
num3 = calculate('mul', 3, 2)
num4 = calculate('div', 3, 2)
print(num1, num2, num3, num4) # 输出:5 1 6 1.5
2、将函数b()作为参数传递:
def b():
pass
def a(func):
func()
a(b) # 将函数b()作为参数传递给a()函数
将函数b()作为另一个函数的参数传递,在这个函数内部调用函数b()。
demo:
def calculate(method, x, y):
return method(x, y)
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
num1 = calculate(addition, 3, 2)
num2 = calculate(subtraction, 3, 2)
num3 = calculate(multiplication, 3, 2)
num4 = calculate(division, 3, 2)
print(num1, num2, num3, num4) # 输出:5 1 6 1.5
or:
def half(method, x, y):
return method(0.5 * x, 0.5 * y)
def double(method, x, y):
return method(2 * x, 2 * y)
def ratio(method, x, y, k):
return method(k * x, k * y)
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
num1 = half(addition, 3, 2)
num2 = double(subtraction, 3, 2)
num3 = ratio(multiplication, 3, 2, 5)
print(num1, num2, num3) # 输出:2.5 2 150
3、使用全局变量:
将函数b()定义为全局变量,这样就可以在a()函数外部访问到函数b()。
def b():
pass
global_func_b = b # 将函数b()定义为全局变量
def a():
global_func_b() # 在a()函数内部调用全局变量中的函数b()
demo:
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
add = addition
sub = subtraction
mul = multiplication
div = division
cals = [add, sub, mul, div]
def calculate(x, y):
for cal in cals:
result = cal(x, y)
print(result)
calculate(3, 2)
# 输出:
5
1
6
1.5
这种方法可以实现一些函数功能的顺序和选择性执行