程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Compare c++ with Python and talk about pointers and references

編輯:Python

0 introduction
The pointer (Pointer) yes C、C++ as well as Java、Go A very central and important concept of language , And quote (Reference) It's an equally important concept built on pointers .

Pointer is necessary and important for any programming language , although Python The concept of pointer is deliberately blurred and limited , But the pointer is for Python It is still a topic that must be discussed in depth .

This article is based on C++ And Python, it has been reviewed that Python Some behaviors related to pointers and references in .

1 What is a pointer ? Why do I need a pointer ?
The pointer has two meanings :

(1) A pointer type that refers to a data type , Such as the type of shaping pointer 、 Pointer pointer type

(2) It refers to a type of variable with memory address , That is, pointer variable

The two meanings of the pointer are closely related : As a variable , You can get a memory address through a pointer , So you're ready to access the values on this address ; As a type , It determines the correct offset length of the memory address , It should be equal to the unit memory size of the current type .

If a pointer is missing a pointer type , namely void *, Obviously , Although it saves the memory address , But this is just a starting address , The pointer will not know the offset from the starting point back , Thus, the pointer resolving operation is rejected ; And if a pointer is missing an address , namely nullptr, It can't read the memory in a specific location at all .

The main meaning of the existence of the pointer is as follows :

  • Carrying through malloc、new、allocator And so on
  • bring pass-by-pointer Make it possible

pass-by-pointer The benefits include, but are not limited to :

  • Avoid copying values that are meaningless to arguments , Significant efficiency improvements
  • The ability to modify a variable is not limited to the scope of the variable itself
  • bring swap、 move constructor 、 Operations such as mobile assignment operation can only be performed on the pointer inside the data structure , Thus avoiding the temporary object 、 The whole memory operation of the source and other objects after the move

thus it can be seen , Pointer related operations are necessary or very important for programming .

2 C++ Citation in
stay C++ in , References have properties similar to pointers , But more invisible and strict .C++ There are two kinds of quotations :

2.1 lvalue reference
The lvalue reference is bound to lvalue in its initialization phase , And there is no rebinding .

An lvalue reference has almost the same properties as the bound lvalue , The only difference is decltype Statement :

int numA = 0, &lrefA = numA; // Binding an lvalue
cout << ++lrefA << endl; // Use the lvalue reference as lvalue & rvalue
decltype(lrefA) numB = 1; // Error!

Left quoting is often used in pass-by-reference:

void swap(int &numA, int &numB)
{
int tmpNum = numA;
numA = numB;
numB = tmpNum;
}
int main()
{
int numA = 1, numB = 2;
swap(numA, numB);
cout << numA << endl << numB << endl; // 2 1
}

2.2 Right quoting
The right value reference is bound to the right value at its initialization stage , It is often used for move constructors and move assignment operations . In these occasions , The move constructor and move assignment take over the moved object through the right value reference .

Right value references are independent of the content of this article , So I won't go into details here .

3 Python Citation in
3.1 Python There is no reference
It can be seen from the above discussion that , although “ quote ” about Python Is a very common term , But it's obviously not accurate —— because Python There is no right to left / Binding operation of right value , So there is no left quotation , There is no right value reference .

3.2 Python Pointer operation of
It's not hard to find out , although Python There is no reference , But its variable behavior and pointer behavior have a high degree of similarity , This is mainly reflected in the following aspects :

  • In any case ( Include assignments 、 Parameter passing, etc ) There is no explicit value copy , When this happens , Only one reference count increase
  • Variables can be rebound ( Corresponds to a no top layer const(top-level const) The pointer to )
  • In some cases ( This is discussed in detail below ), The original value can be modified by function arguments

thus it can be seen ,Python Variables are more like ( Something incomplete ) Pointer to the variable , Instead of quoting variables .

3.2.1 Constructor returns pointer
about Python Description of , There is a very common saying :“ Everything is the object ”.

But in this sentence , There is a very important fact that is often ignored : Object is a value , Not a pointer or reference .

therefore , The exact description of this sentence should be corrected to :“ Everything is ( Something incomplete ) The pointer ”. Although the modified description is abstract , But it's more accurate .

And because objects come from constructors , So far we know :Python The constructor of will construct an anonymous object , And returns a pointer to this object .

This is a Python The first important connection with the pointer .

Describe... In code , about Python Code :

sampleNum = 0

It's not like C++ Code :

int sampleNum = 0;

It's more like :

int __tmpNum = 0, *sampleNum = &__tmpNum;
// perhaps :
shared_ptr<int> sampleNum(new int(0));

3.2.2 __setitems__ Operation will implicitly resolve pointer

Python Another important connection with the pointer is Python Implicit pointer removal behavior of .

although Python There is no explicit pointer operation , but ( Yes and no )__setitems__ Operation will implicitly resolve pointer , To modify a variable by this method is equivalent to modifying the original value of the variable by solving the pointer operation .

This nature means :

  1. Anything that doesn't involve __setitems__ All operations of will become pointer rebinding .

about Python Code :

numList = [None] * 10
# Rebinding
numList = [None] * 5

It is equivalent to :

int *numList = new int[10];
// Rebinding
delete[] numList;
numList = new int[5];
delete[] numList;

thus it can be seen , Yes numList Non - __setitems__ operation , Lead to numList Is bound to a new pointer .

  1. Any involvement __setitems__ All operations of will become pointer operations .

because Python Highly dependent on hash table ,“ involve __setitems__ The operation of ” stay Python It's actually a very wide range of behaviors , This mainly includes :

  • Index operation on array
  • Search operation for hash table
  • involve __setattr__ The operation of ( because Python take attribute Store in hash table , therefore __setattr__ The operation will eventually be some kind of __setitems__ operation )

Let's use a slightly more complex example to illustrate this :

For the following Python Code :

class Complex(object):
def __init__(self, real = 0., imag = 0.):
self.real = real
self.imag = imag
def __repr__(self):
return '(%.2f, %.2f)' % (self.real, self.imag)
def main():
complexObj = Complex(1., 2.)
complexObj.real += 1
complexObj.imag += 1
# (2.00, 3.00)
print(complexObj)
if __name__ == '__main__':
main()

It is equivalent to :

class Complex
{
public:
double real, imag;
Complex(double _real = 0., double _imag = 0.): real(_real), imag(_imag) {}
};
ostream &operator<<(ostream &os, const Complex &complexObj)
{
return os << "(" << complexObj.real << ", " << complexObj.imag << ")";
}
int main()
{
Complex *complexObj = new Complex(1., 2.);
complexObj->real++;
complexObj->imag++;
cout << *complexObj << endl;
delete complexObj;
return 0;
}

thus it can be seen , Whether it's int、float This simple Python type , Or our custom class , Its construction behavior is similar to the use of new Construct object and return pointer .

And in Python Any reference to “.” and “[]” The operation of , Are similar to “->” or “*” Pointer operation .

4 Postscript
This paper discusses Python Variables and pointers 、 Quote the relationship between the two concepts , The main argument is “Python There is no reference ” as well as “Python A variable behaves like a defective pointer ” Two arguments .

The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved