Python 中不可訪問的變數

當您使用多種語言進行編碼時,您通常需要深入挖掘以找到在特定語言中不是很明顯的問題的答案。我的問題是閉包是否可以在 python 中模擬真正的私有變數(即與 __ mangling 方法相反,它確實無法訪問)。

我決定測試這是否適用於閉包,如下所示

def 外(a,b): 類 此: 透過 #—————————————— # 真正的私有變數和方法放在這裡 這。a = a 這。b = b def sum_ () : 返回this。a + this。b def product_ () : 返回this。a * this。b def set_nums_ (a, b) : this。a, this。b = a, b #—————————————— # 公共變數和方法放在這裡 class inner : def get_nums (self) : return this。a, this。乙 def set_nums (self, a, b) : set_nums_(a,b) def sum (self) : 返回sum_() def product (self) : return product_() 返回內部()

結果:

>> > x = 外層( 5 , 3 ) >> > x。get_nums()( 5 , 3 ) >> > x。set_nums( 5 , 4 ) >> > x。get_nums()( 5 , 4 ) >> > x。product() 20 >> > x<__ main_ _在。outer。。inner物件0x0000023C581E21C0 > >> >

耶!似乎它有效。

當然,進一步挖掘表明,每個 python 物件都有

__closure_

_ 屬性,您可以透過它訪問該物件的閉包,並且更改上面“私有”變數的值(繞過 set_nums 方法)只是一個問題:

>> > 漏洞 = x。sum。__closure_ _ [ 0 ]。cell_contents。__closure_ _ [ 0 ]。cell_contents >> > 漏洞<類‘ __main__。外部。。這個’> >> > loophole。a = 8 >> > loophole。b = 9 >> > x。get_nums()( 8 , 9 ) >> >