单个列表元素

时间:2016-03-03 21:30:03

标签: python python-3.x

全部,我有一个包含多个列表对象的类,定义如下:

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函数。以下输出显示了奇怪之处:<​​/ p>

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方法来实现设置/获取特定列表元素的目标?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]