發表文章

目前顯示的是 1月, 2020的文章

[Python] Name Mangling 的大範圍攻擊

早安,真是好久不見了,這學期快忙翻,而這一篇文只是確認生存用的,所以並不會太長。 Name Mangling  在 Python 中撰寫 class 時,只要在屬性名字的前面加上兩個底線(如 __spam),這個屬性的名字最後就會被重組成 _Cls__spam 這樣的形式,這項技術稱作 Name Mangling,提供了類似其他語言的私用屬性。  但要注意的是,就如前面所提到的,類別外部的實例依舊可用重組後的名稱來存取該屬性,所以這並不能做為防止有心人士修改重要資料的方法;事實上,Name Mangling 的存在是為了避免外界對特定屬性的意外存取,或不小心覆寫了父類別的屬性、方法。 class MyClass: def __init__(self): self.__bar = 1 m = MyClass() print(m._MyClass__bar) # 1  但其實,Name Mangling 有個鮮為人知的 陰謀 ... 哪些東西會被 Mangling?  「這話是什麼意思?不就是兩個底線開頭的屬性嗎?」看到標題後,有些人應該會這麼問。的確,像上例的 __bar 會是重組的目標,但其實,還有一些 東西 也是。  根據 Python 官方文件表示: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores , it is considered a private name of that class.  ...  This transformation is independent of the syntactical context in which the identifier is used .  前面的粗體字說明了被重組的名稱必須以 2 個或以上的底線所開頭,且結尾最多只有一個底線;而後面的粗體則是說,這個 mangling 轉換並不侷限於特定的語境(syntactical context),亦即不只有 self.__spam 這裡的 _