Home  >  Article  >  Backend Development  >  Does python have pointers?

Does python have pointers?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-18 17:10:1126453browse

Python has a good encapsulation of pointers. Everything is an "object", and every object has a "variable" pointing to it. This "variable" is a "pointer". Like Java, it cannot move randomly or perform calculations. Including a function is also an "object". Pointing a variable to it points to the entry address of the function.

Does python have pointers?

#The pointer in C that points to the function entry address is called a function pointer. Therefore, we also borrow this term from Python.

For example, I write a sorting code segment and use sort in STL:

int arr[10]={5,8,4,7,6,5,7,4,2,9};
std::sort(arr,arr+10);

The default is ascending order. If I want special sorting criteria, I have to provide a third parameter. The third parameter is a function pointer. The principle of sort is that assuming that b is before a in the original sequence, the exchange occurs when the return value of the function called by the function pointer pf(a,b) is true. When false is returned, it is related to the sorting algorithm. For example, sort is an unstable sort, so it is still possible to exchange positions when the two numbers are equal.

Related recommendations: "python video tutorial"

We write a descending sort. Then you need to write a comparison function cmp first:

bool cmp(int a,int b)
{
    return a>b;//当后面的数大于前面时交换
}

Then, the function name is its entry address, so we pass it in:

std::sort(a,a+10,cmp);

It is similar in Python, assuming there is a list The sorting function Sort(list, cmp)

Then, cmp is also an "object", and it can pass in the function entry address. The calling statement is as follows:

def cmp(a,b):return a>b
li=[5,8,4,7,6,5,7,4,2,9]
Sort(li,cmp)

It is similar to the function of a function pointer.

The above is the detailed content of Does python have pointers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn