python對象類型有哪些,詳解Python對象屬性

 2023-10-04 阅读 39 评论 0

摘要:在面向對象編程中,公開的數據成員可以在外部隨意訪問和修改,很難控制用戶修改時新數據的合法性。解決這一問題的常用方法是定義私有數據成員,然后設計公開的成員方法來提供對私有數據成員的讀取和修改操作,修改私有數據成員時可以對值進行合法性

在面向對象編程中,公開的數據成員可以在外部隨意訪問和修改,很難控制用戶修改時新數據的合法性。解決這一問題的常用方法是定義私有數據成員,然后設計公開的成員方法來提供對私有數據成員的讀取和修改操作,修改私有數據成員時可以對值進行合法性檢查,提高了程序的健壯性,保證了數據的完整性。屬性結合了公開數據成員和成員方法的優點,既可以像成員方法那樣對值進行必要的檢查,又可以像數據成員一樣靈活的訪問。

python對象類型有哪些?Python 2.x中屬性的實現有很多不如人意的地方,在Python 3.x中,屬性得到了較為完整的實現,支持更加全面的保護機制。如果設置屬性為只讀,則無法修改其值,也無法為對象增加與屬性同名的新成員,同時,也無法刪除對象屬性。例如:

>>> class Test:

python六大基本數據類型? def __init__(self, value):

self.__value = value ?#私有數據成員

@property ?#修飾器,定義屬性,提供對私有數據成員的訪問

def value(self): ??#只讀屬性,無法修改和刪除

return self.__value

>>> t = Test(3)

>>> t.value

3

>>> t.value = 5 ??#只讀屬性不允許修改值

Traceback (most recent call last):

? File "<pyshell#151>", line 1, in <module>

? ? t.value = 5

AttributeError: can't set attribute

>>> t.v=5 ??#動態增加新成員

>>> t.v

5

>>> del t.v #動態刪除成員

>>> del t.value ?#試圖刪除對象屬性,失敗

Traceback (most recent call last):

? File "<pyshell#152>", line 1, in <module>

? ? del t.value

AttributeError: can't delete attribute

>>> t.value

3

下面的代碼則把屬性設置為可讀、可修改,而不允許刪除。

>>> class Test:

def __init__(self, value):

self.__value = value

def __get(self): ??#讀取私有數據成員的值

return self.__value

def __set(self, v): #修改私有數據成員的值

self.__value = v

value = property(__get, __set) ?#可讀可寫屬性,指定相應的讀寫方法

def show(self):

print(self.__value)

>>> t = Test(3)

>>> t.value #允許讀取屬性值

3

>>> t.value = 5 ? #允許修改屬性值

>>> t.value

5

>>> t.show() ?#屬性對應的私有變量也得到了相應的修改

5

>>> del t.value ?#試圖刪除屬性,失敗

Traceback (most recent call last):

? File "<pyshell#152>", line 1, in <module>

? ? del t.value

AttributeError: can't delete attribute

當然,也可以將屬性設置為可讀、可修改、可刪除。

>>> class Test:

def __init__(self, value):

self.__value = value

def __get(self):

return self.__value

def __set(self, v):

self.__value = v

def __del(self): ? #刪除對象的私有數據成員

del self.__value

value = property(__get, __set, __del) ? #可讀、可寫、可刪除的屬性

def show(self):

print(self.__value)

>>> t = Test(3)

>>> t.show()

3

>>> t.value

3

>>> t.value = 5

>>> t.show()

5

>>> t.value

5

>>> del t.value

>>> t.value ?#相應的私有數據成員已刪除,訪問失敗

Traceback (most recent call last):

? File "<pyshell#165>", line 1, in <module>

? ? t.value

? File "<pyshell#157>", line 6, in __get

? ? return self.__value

AttributeError: 'Test' object has no attribute '_Test__value'

>>> t.show()

Traceback (most recent call last):

? File "<pyshell#166>", line 1, in <module>

? ? t.show()

? File "<pyshell#157>", line 17, in show

? ? print(self.__value)

AttributeError: 'Test' object has no attribute '_Test__value'

>>> t.value =1 ?#為對象動態增加屬性和對應的私有數據成員

>>> t.show()

1

>>> t.value

1

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/112801.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息