Python - 私有方法,專有方法

Python的私有方法:以'__'雙劃線開頭,但不以雙劃線結尾, __privateMethod

專有方法:以雙劃線開頭和結尾, __init__

e.g

class Person:
    def __init__(self,name):
        self.name = "Person"

    def __getName(self):
        return self.name
<pre style="color: rgb(0, 0, 0); font-family: 'Courier New'; font-size: 9pt; background-color: rgb(255, 255, 255);"><span style="background-color: rgb(255, 228, 255);">aPerson</span> = Person(<span style="color: rgb(0, 128, 0); font-weight: bold;">'test'</span>)
<span style="background-color: rgb(228, 228, 255);">aPerson</span>.getName()


結果: aPerson.getName()
AttributeError: Person instance has no attribute 'getName', 因爲是私有所以會報錯哦。

而__init__就是一個初始化函數,典型的專有函數


發佈了43 篇原創文章 · 獲贊 12 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章