執行個體講解Python中的私人屬性_python

來源:互聯網
上載者:User

在Python中可以通過在屬性變數名前加上雙底線定義屬性為私人屬性,如例子:

複製代碼 代碼如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定義私人屬性
        self.__name = "wangwu"
        
        # 普通屬性定義
        self.age = 19
        
a = A()
 
# 正常輸出
print a.age
 
# 提示找不到屬性
print a.__name

執行輸出:
複製代碼 代碼如下:

Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in <module>
    print a.__name
AttributeError: A instance has no attribute '__name'

訪問私人屬性__name時居然提示找不到屬性成員而不是提示許可權之類的,於是當你這麼寫卻不報錯:
複製代碼 代碼如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定義私人屬性
        self.__name = "wangwu"
        
        # 普通屬性定義
        self.age = 19
        
 
a = A()
 
a.__name = "lisi"
print a.__name

執行結果:
1
lisi
在Python中就算繼承也不能相互訪問私人變數,如:
複製代碼 代碼如下:

#! encoding=UTF-8
 
class A:
    def __init__(self):
        
        # 定義私人屬性
        self.__name = "wangwu"
        
        # 普通屬性定義
        self.age = 19
        
 
class B(A):
    def sayName(self):
        print self.__name
        
 
b = B()
b.sayName()

執行結果:
複製代碼 代碼如下:

Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in <module>
    b.sayName()
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in sayName
    print self.__name
AttributeError: B instance has no attribute '_B__name'

或者父類訪問子類的私人屬性也不可以,如:
複製代碼 代碼如下:

#! encoding=UTF-8
 
class A:
    def say(self):
        print self.name
        print self.__age
        
 
class B(A):
    def __init__(self):
        self.name = "wangwu"
        self.__age = 20
 
b = B()
b.say()

執行結果:
複製代碼 代碼如下:

wangwu
Traceback (most recent call last):
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in <module>
    b.say()
  File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 6, in say
    print self.__age
AttributeError: B instance has no attribute '_A__age'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.