单类python列表 [英] single class python list

查看:79
本文介绍了单类python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在派生对象中重写python列表对象中的每个set方法,以使该列表中的每个项目都属于特定类?

How can every set method in python's list object be overridden in a derived object such that every item in that list is of a specific class?

考虑

class Index(int):
    pass


class IndexList(list):

    def __init__(self, int_list):
        for el in int_list:
            self.append(Index(el))

    def __setitem__(self, key, val):
        super(IndexList, self).__setitem__(key, Index(val))

    # override append insert etc...

是否可以在不直接覆盖将元素添加到列表的每个函数的情况下完成此操作?我期望只需覆盖__setitem__就足够了.

Can this be done without directly overriding every single function that adds elements to the list? I expected simply overriding __setitem__ was enough.

例如,如果未覆盖append.

ilist = IndexList([1,2])
ilist.append(3)

for i in ilist:
    print(isinstance(i, Index)) # True, True, False

推荐答案

您必须直接实现各种功能;底层的C实现不会为每次更改都调用__setitem__,因为直接操纵(动态增长的)C数组要有效得多.

You'll have to implement the various directly; the underlying C implementation does not call __setitem__ for each and every change, as it is far more efficient to directly manipulate the (dynamically grown) C array.

看看 collections抽象库类,特别是MutableSequence ABC上的类,以了解所有方法都可以使您的列表发生变异,以保持类型不变,您需要实现insertappendextend__iadd__.

Take a look at the collections abstract base classes, specifically at the MutableSequence ABC, to get an idea of what methods all can mutate your list, to maintain your type invariant you'd need to implement insert, append, extend and __iadd__.

更好的是,您可以使用collections.MutableSequence()类作为list的替代基类.这是一个纯python实现,可以将许多方法强制转换为对一组核心方法的调用;您只需要提供__len____getitem____setitem____delitem__insert的实现;在表的 Abstract Methods 列中命名的任何方法.

Better still, you can use the collections.MutableSequence() class as an alternative base class to list; this is a pure-python implementation that does cast many of those methods as calls to a core set of methods; you'd only need to provide implementations for __len__, __getitem__, __setitem__, __delitem__ and insert; any method named in the Abstract Methods column of the table.

class IndexList(collections.MutableSequence):
    def __init__(self, int_list):
        self._list = []
        for el in int_list:
            self.append(Index(el))

    def __len__(self): return len(self._list)
    def __getitem__(self, item): return self._list[item]
    def __delitem__(self, item): del self._list[item]

    def __setitem__(self, index, value):
        self._list.key[index] = Index(value)

    def insert(self, index, value):
        self._list.insert(index, Index(value))

这篇关于单类python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆