轉自:http://blog.csdn.net/ccat/archive/2003/04/30/8349.aspx
致 謝:這是一篇譯稿,原作者是一位NASA的程序員,非常感謝他在Python社區及時、詳細的爲我解答了問題,並在講解中解說了一些Python的相關知 識,還寬容的對待我蹩腳的英語。感謝他同意我將他的來信介紹給大家。這是一位謙和有禮又博學多才的朋友。他幫我理解Python之美,也讓我看到人性之 美。
問:Python中爲什麼沒有swap(a, b)方法?我們在Python中如何交換對象?
Python 不使用這種方式(swap(a, b))。Python以引用方式管理對象,你可以交換引用,但通常不能交換內存中的對象值。當然你也不需要這樣做。
在C++中這種函數用來交換“a和b的值”。在Python中,a和b的值不會發生交換,但位於當前命名空間中的標記(如a和b)是可以交換的。而對象本身是仍然保留。
所以與其調用一個swap(a, b),你倒不如使用:a,b = b,a。
通常python函數不會混淆它們的命名空間,所以它不能像C++的swap(&a, &b)那樣進行引用操作。
因此,在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
namespace) to do it like this:
不過下面這段代碼不可能像我們希望的那樣工作(全局命名空間和局部命名空間是隔離的):
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.
在類中,你可以構造一個命名空間來操作可調用的對象(類實例方法),事實上,這意味着也許可以實現一個swap()方法。但是它們仍然只是操作命名空間中的對象引用,而不會交換對象本身(或者它們在機器內存中的數據)。以下只是一個示例,並不表示它們有什麼實用性:
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