gpt4 book ai didi

python - 单个列表元素的属性 setter

转载 作者:太空宇宙 更新时间:2023-11-04 10:15:11 26 4
gpt4 key购买 nike

所有,我有一个类有几个列表对象,定义如下:

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] <br/>
after: [None, 'try', None, None, None, None] # accessing single element is achieved<br/> # , but not through @channels.setter!<br/>
inside: [None, 'try', None, None, None, None] try # only here we're<br/>
check: try2 # at least the setter works..<br/>

由于我需要在设置 channels 的单个元素时运行逻辑,因此这种行为是有问题的。我想知道导致这种行为的底层 python 机制是什么,它是如何被覆盖的?是否有更pythonic的方式来实现设置/获取特定列表元素的目标?

最佳答案

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

关于python - 单个列表元素的属性 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35783418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com