微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python3回调函数

先看一下C/C++的回调函数实例:

#include<iostream>
 
using namespace std;
 
int computer(int a,int b,int(*func)(int,int)) {
	return func(a,b);
}
 
int max(int a,int b) {
	return (a > b ? a : b);
}
 
int min(int a,int b) {
	return (a > b ? b : a);
}
 
int sum(int a,int b) {
	return a + b;
}
 
int main() {
	int a,b,res;
	cout << "请输入整数a:"; cin >> a;
	cout << "请输入整数b:"; cin >> b;
	res = computer(a,&max);
	cout << "Max of " << a << " and " << b << " is " << res << endl;
	res = computer(a,&min);
	cout << "Min of " << a << " and " << b << " is " << res << endl;
	res = computer(a,&sum);
	cout << "Sum of " << a << " and " << b << " is " << res << endl;
	return 0;
}

结果:

 

再看python的情况:

def computer(a,func):
    return func(a,b)
 
 
def max(a,b):
    return [a,b][a < b]
 
 
def min(a,b][a > b]
 
 
def sum(a,b):
    return str(int(a) + int(b))
 
 
if __name__ == "__main__":
    a = input("请输入整数a:")
    b = input("请输入整数b:")
    res = computer(a,max)
    print("Max of " + a + " and " + b + " is " + res)
    res = computer(a,min)
    print("Min of " + a + " and " + b + " is " + res)
    res = computer(a,sum)
    print("Sum of " + a + " and " + b + " is " + res)

结果:

 

注意:一开始在测试上面python代码的时候,我没有加类型转换str()和int(),出现了输出 Sum of 5 and 12 is 512 的情况。看来python用起来是方便,但是编译器帮我们做了太多的事情,有时候会让我们忽略一些程序的本质,所以不能光学python啊,c++还是要多看看,有助于对程序本质的理解。

        说白了,回调函数和普通函数在定义的时候没有什么区别,只有在调用时才看出来是不是回调函数,正常调用就是普通函数,作为一个函数的参数在需要的时候分情况调用,就是回调函数

        另外,回调函数还可以进行异步调用,即非阻塞调用,通常用在多线程或者多进程中。暂时没用到,先了解。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐