Python 物件導向 --- 私人屬性和私人方法

來源:互聯網
上載者:User

標籤:私人方法   分享   名稱   特殊   init   開發   http   python   私人屬性   

01,應用情境及定義方式應用情境
  • 在實際開發中,對象某些屬性或方法 可能只希望 在對象的內部被使用,而 不希望被外部存取到
  • 私人屬性 就是 對象 不希望公開的 屬性
  • 私人方法 就是 對象 不希望公開的 方法
定義方式
  • 定義屬性或方法時,在 屬性名稱或者方法名前 增加連個底線,定義的就是 私人 屬性或方法

    class Women:        def __init__(self, name):            self.name = name            self.__age = 18            # def __secret(self):        def secret(self):            # 在對象的方法內部,是可以訪問對象的私人屬性的            print("%s 的年齡是 %d" % (self.name, self.__age))            namei = Women("娜美")    # 私人屬性和私人方法,在外界不能直接別訪問    # namei.__age()    # namei.__secret()    namei.secret()        #  結果呈現    娜美 的年齡是 18
02,偽私人屬性和私人方法

提示:在日常開發中,不要使用這種方法,訪問對象的 私人屬性 或 私人方法

python 中,並沒有 真正意義私人

  • 在給 屬性、方法 命名時,實際是對 名稱 做了一些特殊處理,使得外界無法訪問到
  • 處理方式: 在 名稱 面前加上 __類名 => __類名__名稱
    class Women():        def __init__(self, name):            self.name = name            self.__age = 18            def __secret(self):        # def secret(self):            # 在對象的方法內部,是可以訪問對象的私人屬性的            print("%s 的年齡是 %d" % (self.name, self.__age))            namei = Women("娜美")    # 私人屬性和私人方法,在外界不能直接別訪問    # namei.__age()    namei._Women__secret()    # namei.secret()        # 結果呈現    娜美 的年齡是 18

Python 物件導向 --- 私人屬性和私人方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.