看板 Python 關於我們 聯絡資訊
我今天寫了一支測試用的程式 : >>> 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
sheauhei:用property? 09/30 13:33
sheauhei:http://snippets.dzone.com/posts/show/954 <- 例子 09/30 13:33
Falldog:overwrite __setattr__去判斷 XD 09/30 13:41
anrris:S 大的意思是否是將例子裡面的set_x寫成丟個error出來 ^^? 09/30 13:48
anrris:這個方法感覺滿不賴的 ^^ 09/30 13:49
sbrhsieh:Non-data descriptor 09/30 23:00
sbrhsieh:http://ppt.cc/FKrM Descriptors 09/30 23:07
cobrasgo:轉成tuple應該就可以了吧 10/01 12:37
cobrasgo:class內部用list,傳給外部轉成tuple 10/01 12:37
anrris:請問樓上的方法有簡單實做的 code 嗎 ? 10/02 05:43
sbrhsieh:immutable attribute value/readonly attribute 是兩回事 10/02 14:07