python 存取權限

來源:互聯網
上載者:User

標籤:建議   exp   訪問   test   相關   dict   and   post   名稱   

存取權限
  • 許可權:

    • 公有的:類中的普通屬性和方法,預設都是公有的,可以在類的內部、外部、子類中使用

    • 私人的:定義是在前面加兩個‘_‘,只能在本類的內部使用,不能再外部及子類中使用

  • 樣本:

  • class Person:      def __init__(self, name, age):          self.name = name          # 在屬性的前面添加兩個‘_‘,外部存取,系統內部的除外          # 預設的屬性名稱:__age => _Person__age          self.__age = age      def eat(self):          print(‘民以食為天‘)      # 在方法的前面添加兩個‘_‘      def __inner(self):          print(‘私人方法,不想讓外部調用‘)      def test(self):          # 在類的內部可以訪問私人的屬性和方法          print(self.__age)          self.__inner()            p = Person(‘老王‘, 50)# 預設所有的屬性和方法都是公有的,就是在類的外面可以直接使用p.eat()print(p.name)# 一下兩句會報錯,提示沒有相關的屬性或方法# p.__inner()# print(p.__age)# print(p.__dict__)# 可以通過系統修改的名稱找到,但是強烈建議不要這樣使用print(p._Person__age)p._Person__inner()p.test()class Man(Person):    def test(self):        # print(self.__age)        # self.__inner()        print(‘子類無法使用父類私人的屬性和方法‘)m = Man(‘木蓋‘, 24)m.test()

     

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.