Why does Python need SWAP (A, B)

zhaozj2021-02-11  259

Acknowledgments: This is a translation. The original author is a NASA programmer. I am very grateful to him in the Python community. I will answer questions in a timely manner, and explain some Python's related knowledge, and tolerant Treat me my foot. Thank He agreed to introduce his letter to everyone. This is a modest and courteous friend. He helped me understand the beauty of Python and let me see the beauty of humanity. Q: Why doesn't Python do not have a SWAP (A, B) method? How do we exchange objects in Python?

Python does not use this method (SWAP (A, B)). Python manages objects in a reference, you can exchange references, but usually cannot exchange object values ​​in memory. Of course, you don't need to do this.

This function is used to exchange "A and B value" in C . In Python, the values ​​of A and B do not exchange, but markers in the current namespace (such as A and B) can be exchanged. The object itself is still retained.

So there is a swap (a, b) that is called, you are not as used as: A, B = B, A.

Usually the Python function does not confuse their namespace, so it cannot be cited like C SWAP (& A, & B).

Therefore, you should do this in Python:

A = 1

B = 2

DEF SWAP (T1, T2):

Return T2, T1

A, b = swap (a, b) #After this point, a == 2 and b == 1

But there is not way (Other Than Abusing globals or the module

n i i t t:

However, the code below is impossible to work as we hope (global namespace and local namespace are isolated):

A = 1

B = 2

DEF SWAP (T1, T2):

T2, T1 = T1, T2

Return

SWAP (A, B)

#After this point, a == 1 and b == 2. The calling namespace IS

# NOT CHANGED.

In the class, you can construct a namespace to operate the object (class instance method), in fact, this means that a swap () method can be implemented. But they are still just an object reference in the namespace, without switching the object itself (or the data they in the machine). The following is just an example and does not mean what practicality they have:

Class Pair:

DEF __INIT __ (Self, T1, T2):

Self.t1 = T1

Self.t2 = T2

DEF GET (Self):

Return Self.t1, Self.t2

DEF SWAP (SELF):

Self.t1, self.t2 = self.t2, self.t1

A = 1

B = 2

Pair = Pair (a, b)

Pair.get () # returns 1, 2

Pair.Swap () # Changes the namespace of the pair object

Pair.get () # returns 2,1

a == 1

B == 2 # The a and b labels Did Not Change

转载请注明原文地址:https://www.9cbs.com/read-4581.html

New Post(0)