Python 定義只讀屬性的實現(xiàn)方式
Python是面向?qū)ο?OOP)的語言, 而且在OOP這條路上比Java走得更徹底, 因為在Python里, 一切皆對象, 包括int, float等基本數(shù)據(jù)類型.
在Java里, 若要為一個類定義只讀的屬性, 只需要將目標屬性用private修飾, 然后只提供getter()而不提供setter(). 但Python沒有private關鍵字, 如何定義只讀屬性呢? 有兩種方法, 第一種跟Java類似, 通過定義私有屬性實現(xiàn). 第二種是通過__setattr__.
通過私有屬性
Python里定義私有屬性的方法見 http://m.fzitv.net/article/181953.htm.
用私有屬性+@property定義只讀屬性, 需要預先定義好屬性名, 然后實現(xiàn)對應的getter方法.
class Vector2D(object): def __init__(self, x, y): self.__x = float(x) self.__y = float(y) @property def x(self): return self.__x @property def y(self): return self.__y if __name__ == "__main__": v = Vector2D(3, 4) print(v.x, v.y) v.x = 8 # error will be raised.
輸出:
(3.0, 4.0) Traceback (most recent call last): File ...., line 16, in <module> v.x = 8 # error will be raised. AttributeError: can't set attribute
可以看出, 屬性x是可讀但不可寫的.
通過__setattr__
當我們調(diào)用obj.attr=value時發(fā)生了什么?
很簡單, 調(diào)用了obj的__setattr__方法. 可通過以下代碼驗證:
class MyCls(): def __init__(self): pass def __setattr__(self, f, v): print 'setting %r = %r'%(f, v) if __name__ == '__main__': obj = MyCls() obj.new_field = 1
輸出:
setting 'new_field' = 1
所以呢, 只需要在__setattr__ 方法里擋一下, 就可以阻止屬性值的設置, 可謂是釜底抽薪.
代碼:
# encoding=utf8
class MyCls(object):
readonly_property = 'readonly_property'
def __init__(self):
pass
def __setattr__(self, f, v):
if f == 'readonly_property':
raise AttributeError('{}.{} is READ ONLY'.\
format(type(self).__name__, f))
else:
self.__dict__[f] = v
if __name__ == '__main__':
obj = MyCls()
obj.any_other_property = 'any_other_property'
print(obj.any_other_property)
print(obj.readonly_property)
obj.readonly_property = 1
輸出:
any_other_property readonly_property Traceback (most recent call last): File "...", line 21, in <module> obj.readonly_property = 1 ... AttributeError: MyCls.readonly_property is READ ONLY
以上這篇Python 定義只讀屬性的實現(xiàn)方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
tensorflow從ckpt和從.pb文件讀取變量的值方式
這篇文章主要介紹了tensorflow從ckpt和從.pb文件讀取變量的值方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python常見庫matplotlib學習筆記之畫圖文字的中文顯示
在Python中使用matplotlib或者plotnine模塊繪圖時,常常出現(xiàn)圖表中無法正常顯示中文的問題,下面這篇文章主要給大家介紹了關于Python常見庫matplotlib學習筆記之畫圖文字的中文顯示的相關資料,需要的朋友可以參考下2023-05-05
Visual Studio Code搭建django項目的方法步驟
這篇文章主要介紹了Visual Studio Code搭建django項目的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09
Python高階函數(shù)之filter()函數(shù)代碼示例
這篇文章主要介紹了Python高階函數(shù)之filter()函數(shù)代碼示例,獲取了一個序列的時候,想要把一些內(nèi)容去掉,保留一部分內(nèi)容的時候可以使用高效的filter()函數(shù),需要的朋友可以參考下2023-07-07

