Python 定義只讀屬性的實(shí)現(xiàn)方式
Python是面向?qū)ο?OOP)的語(yǔ)言, 而且在OOP這條路上比Java走得更徹底, 因?yàn)樵赑ython里, 一切皆對(duì)象, 包括int, float等基本數(shù)據(jù)類(lèi)型.
在Java里, 若要為一個(gè)類(lèi)定義只讀的屬性, 只需要將目標(biāo)屬性用private修飾, 然后只提供getter()而不提供setter(). 但Python沒(méi)有private關(guān)鍵字, 如何定義只讀屬性呢? 有兩種方法, 第一種跟Java類(lèi)似, 通過(guò)定義私有屬性實(shí)現(xiàn). 第二種是通過(guò)__setattr__.
通過(guò)私有屬性
Python里定義私有屬性的方法見(jiàn) https://www.jb51.net/article/181953.htm.
用私有屬性+@property定義只讀屬性, 需要預(yù)先定義好屬性名, 然后實(shí)現(xiàn)對(duì)應(yīng)的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.__yif __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是可讀但不可寫(xiě)的.
通過(guò)__setattr__
當(dāng)我們調(diào)用obj.attr=value時(shí)發(fā)生了什么?
很簡(jiǎn)單, 調(diào)用了obj的__setattr__方法. 可通過(guò)以下代碼驗(yàn)證:
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__ 方法里擋一下, 就可以阻止屬性值的設(shè)置, 可謂是釜底抽薪.
代碼:
# encoding=utf8class 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] = vif __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_propertyreadonly_propertyTraceback (most recent call last): File '...', line 21, in <module> obj.readonly_property = 1 ... AttributeError: MyCls.readonly_property is READ ONLY
以上這篇Python 定義只讀屬性的實(shí)現(xiàn)方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號(hào)賬號(hào)的實(shí)現(xiàn)代碼2. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問(wèn)題分析3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 解決Python 進(jìn)程池Pool中一些坑5. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼6. Python如何讀寫(xiě)CSV文件7. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介8. ajax請(qǐng)求添加自定義header參數(shù)代碼9. python利用os模塊編寫(xiě)文件復(fù)制功能——copy()函數(shù)用法10. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)
