pythonpython中有指针吗
Python对指针做了良好封装,一切都是“对象”,一切对象都有一个“变量”指向它。这个“变量”就是“指针”。和Java一样,它不可以随机移动,不可以运算。包括函数也是一个“对象”,用一个变量指向它,就是指向函数的入口地址。
C++中指向函数入口地址的指针,叫做函数指针。所以,这一名词我们也借用到Python中。
比如,我写一个排序的代码段,用STL里的sort:
intarr[10]={5,8,4,7,6,5,7,4,2,9};
std::sort(arr,arr+10);
默认是升序排序。如果我想要特殊的排序标准,那就要提供第三个参数。第三个参数就是一个函数指针。sort的原则就是,假设原序列中b在a之前,当函数指针pf(a,b)调用的函数的返回值为true时发生交换。返回false时,和排序的算法有关,比如sort是不稳定排序,所以两数相等时仍有可能交换位置。
我们写一个降序排序。那就需要先写一个比较函数cmp:
boolcmp(inta,intb)
{
returna>b;//当后面的数大于前面时交换
}
然后,函数名就是它的入口地址,所以我们把它传进去:
std::sort(a,a+10,cmp);
Python中也类似,假设有一个列表的排序函数Sort(list,cmp)
那么,cmp也是一个“对象”,它可以传入函数入口地址。调用语句如下:
defcmp(a,b):returna>b
li=[5,8,4,7,6,5,7,4,2,9]
Sort(li,cmp)
也就类似于函数指针的功能。
以上内容为大家介绍了Python培训之python中有指针吗,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






