子类Python列表以验证新项目 [英] Subclass Python list to Validate New Items
问题描述
我想要一个python列表,该列表在外部将其自身表示为其内部列表项的平均值,但在其他方面则表现为列表.如果添加了不能转换为浮点数的项目,则应提高TypeError
.
I want a python list which represents itself externally as an average of its internal list items, but otherwise behaves as a list. It should raise a TypeError
if an item is added that can't be cast to a float.
我遇到的问题是提高TypeError
.对于通过任何列表方法(例如.append
,.extend
,+=
,按切片设置等)添加的无效项,应将其引发.
The part I'm stuck on is raising TypeError
. It should be raised for invalid items added via any list method, like .append
, .extend
, +=
, setting by slice, etc.
是否可以拦截添加到列表中的新项目并对其进行验证?
我尝试重新验证__getattribute__
中的整个列表,但是当调用它时,我只能访问列表的旧版本,而且甚至无法调用初始化,例如+=
或像mylist[0] = 5
这样的切片.
I tried re-validating the whole list in __getattribute__
, but when its called I only have access to the old version of the list, plus it doesn't even get called initialization, operators like +=
, or for slices like mylist[0] = 5
.
有什么想法吗?
推荐答案
继承自 MutableSequence 并实现其所需的方法以及仅属于序列范围之外的任何其他方法,例如
Inherit from MutableSequence and implement the methods it requires as well as any others that fall outside of the scope of Sequences alone -- like the operators here. This will allow you to change the operator manipulations for list-like capabilities while automatically generating iterators and contains capabilities.
如果要检查切片,则需要在__getitem__
(和/或__setitem__
)方法中执行isinstance(key, slice)
.请注意,像myList [0]这样的单个索引不是切片请求,而是像myList [:0]这样的单个索引是实际的切片请求.
If you want to check for slices btw you need to do isinstance(key, slice)
in your __getitem__
(and/or __setitem__
) methods. Note that a single index like myList[0] is not a slice request, but a single index and myList[:0] is an actual slice request.
这篇关于子类Python列表以验证新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!