[問題] 如何讓一個 attribute 成為 not writable 呢 ?

看板Python作者 ( ...)時間13年前 (2010/09/30 12:56), 編輯推噓4(408)
留言12則, 5人參與, 最新討論串1/1
我今天寫了一支測試用的程式 : >>> from numpy import * >>> L = arange(3*3).reshape(3,3) >>> L array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> L.shape (3, 3) >>> L.size 9 >>> L.size = 4 Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> L.size = 4 AttributeError: attribute 'size' of 'numpy.ndarray' objects is not writable >>> 我的問題是 , 對於 numpy 讓我產生的 L array 物件而言 L.size 顯然是它的一個 attribute .. 但是當我要修改 size 的這個 attribute 的時候則會跑出來 'size' of 'numpy.ndarray' object is not writable 的錯誤訊息.. 我今天嘗試的想要模仿這樣的情況, 自己寫一個 class 讓裡面的某些 attribute 也是 not writable 的 .. (我希望那些 attribute 可以被讀取但是不能直接被外部更動 .. 可能有點類似 C++ 裡面的 private 成員, 但是感覺上更直覺更方便) 上網找了半天都找不到相關的說明 .. 不知道有沒有高手可以告訴我如何實做出來這樣的功能 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 98.201.60.113

09/30 13:33, , 1F
用property?
09/30 13:33, 1F

09/30 13:33, , 2F

09/30 13:41, , 3F
overwrite __setattr__去判斷 XD
09/30 13:41, 3F

09/30 13:48, , 4F
S 大的意思是否是將例子裡面的set_x寫成丟個error出來 ^^?
09/30 13:48, 4F

09/30 13:49, , 5F
這個方法感覺滿不賴的 ^^
09/30 13:49, 5F

09/30 23:00, , 6F
Non-data descriptor
09/30 23:00, 6F

09/30 23:07, , 7F
http://ppt.cc/FKrM Descriptors
09/30 23:07, 7F

10/01 12:37, , 9F
轉成tuple應該就可以了吧
10/01 12:37, 9F

10/01 12:37, , 10F
class內部用list,傳給外部轉成tuple
10/01 12:37, 10F

10/02 05:43, , 11F
請問樓上的方法有簡單實做的 code 嗎 ?
10/02 05:43, 11F

10/02 14:07, , 12F
immutable attribute value/readonly attribute 是兩回事
10/02 14:07, 12F
文章代碼(AID): #1Cf1XpdO (Python)