Re: [問題] Python private method...
※ 引述《EntHeEnd (ㄆㄆ)》之銘言:
: 請問一下python 的private到底是怎樣呢
: 粗淺搜尋了一下相關資料
: 提到
: python class
: 以 __開頭宣告的 method會被視作private
: 不會被override
: 例如
: class A:
: def __init__(self):
: print("A")
: self.__A()
: def __A(self):
: print("_A")
: class B(A):
: def __A(self):
: print("_B")
: b = B()
: #執行結果
: #A
: #_A
: 問題來了...
: 那 __init__ 為什麼就可以被override呢...
: 謝謝...
請看官方說法
http://docs.python.org/2/tutorial/classes.html#tut-private
單 _ 開頭是 Convension,
這告訴外人,這是 implementation 細節,沒事不要理它。
雙 __ 開頭,且最多只可以有{一個} 後面的 _,
這個時候會產生 name mangling,
不單單只是個Convension, Intepreter 還會把你的 method 改名。
__XX__
它後面有兩個 _ ,所以不會有 name mangling.
而請不要產生 __XX__ 這種 function name,
它有可能會跟未來的某一版 Python 不相容。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.62.8.191
※ 編輯: timTan 來自: 61.62.8.191 (05/20 00:28)
※ 編輯: timTan 來自: 61.62.8.191 (05/20 00:28)
推
05/20 00:38, , 1F
05/20 00:38, 1F
→
05/20 00:41, , 2F
05/20 00:41, 2F
推
05/20 01:01, , 3F
05/20 01:01, 3F
→
05/20 01:05, , 4F
05/20 01:05, 4F
推
05/20 01:19, , 5F
05/20 01:19, 5F
※ 編輯: timTan 來自: 61.62.8.191 (05/20 01:20)
→
05/20 01:21, , 6F
05/20 01:21, 6F
推
05/20 02:25, , 7F
05/20 02:25, 7F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章