2016-03-03 72 views
1

所有,我有一個幾個列表對象類,定義如下:的屬性設置爲一個單獨的列表元素

class Device: 

    def __init__(self): 
    self._channels = [None]*6 
    self._outputs = [None]*4 

    @property 
    def channels(self): 
    return self._channels 

    @channels.setter 
    def channels(self,value): 
    print("inside:",self.channels, value) 
    self._channels = value 

這裏奇怪的是,在調用device.channels[1] = 'try'作品,但似乎並沒有爲'通過@ setter.channels函數。從下面的輸出顯示古怪:

device = Device() 
print("before:",device.channels) 
device.channels[1] = "try" 
print("after:",frmdeviced.channels) 
device.channels = "try2" 
print("check:",frm4d.channels) 

並且輸出是:


before: [None, None, None, None, None, None] 
after: [None, 'try', None, None, None, None] # accessing single element is achieved
# , but not through @channels.setter!
inside: [None, 'try', None, None, None, None] try # only here we're
check: try2 # at least the setter works..

由於我需要邏輯時的channels單個元件被設置爲運行,這種行爲是有問題的。 我想知道導致這種行爲的基礎python機制是什麼,它是如何被覆蓋?是否有更多pythonic方式來實現設置/獲取特定列表元素的目標?

+1

您需要在'channels'引用的對象上實現'__setitem__',在'Device'上執行它是沒有意義的。 – jonrsharpe

+0

設置列表的一個元素是列表的一個操作,而不是交給列表的'Device'的操作。 – user2357112

回答

3

device.channels[1] = "try"首先要訪問"@property" getter方法,它返回一個列表,然後索引操作將在不在設備上的列表上執行。下面的例子證明它 -

>>> class Device: 

    def __init__(self): 
    self._channels = [None]*6 
    self._outputs = [None]*4 

    @property 
    def channels(self): 
    print("inside @property") 
    return self._channels 

    @channels.setter 
    def channels(self,value): 
    print("inside:",self.channels, value) 
    self._channels = value 


>>> device = Device() 
>>> device.channels[1] = "try" 
inside @property 
+0

@ user2357112,我以前看不到python3.x標記,現在我已經修改了我的答案。感謝您指出它 – AlokThakur

1

要儀器列表,創建一個儀表列表類。 Jupyter會話示例:

In [23]: class MonitoredList(list): 
      def __setitem__(self, index, value): 
       # run special logic here 
       print("setting index {} to {}".format(index, value)) 
       super(MonitoredList, self).__setitem__(index, value) 

In [24]: zz = MonitoredList([None]*6) 

In [25]: zz 
Out[25]: [None, None, None, None, None, None] 

In [26]: zz[3] = 42 
     setting index 3 to 42 

In [27]: zz 
Out[27]: [None, None, None, 42, None, None] 
相關問題