首页 > 解决方案 > python类初始化引用现有列表的自定义类

问题描述

我有从列表继承的 MyList 类。当我传递列表的实例时,即。[0, 3, 5, 1] 到 MyList,如何构造 MyList 避免复制并让自己对其他内容没有复制引用。

我尝试过:

other.__class__ = MyList: 给出类型错误

super(MyList, cls).__new__(other): 给出类型错误

super(MyList, other): 给出类型错误

最后与

self[:] = other[:]: 给出 id(self) != id(other)

当我在 MyList 中就地执行一些操作时,简单的MyList([0, 1, 3, 4])也无法解决问题。


class MyList(list):
   def __new__(cls, other):
        other.__class__ = MyList
        return other
   # add bunch of methods that work inplace on list
   def merge(self,):
       pass
   def sort(self,):
       pass
   def find(self, x):
       pass
   def nextNonMember(self, x): 
       pass

我想避免的另一种方法是:


class MyNotSoFancyList(object):
     def __init__(self, other):
         self.list = other

我希望有这种行为:

t = [0, 1, 3, 100, 20, 4]
o = MyList(t)
o.sort()
assert(t == o)

当我不了解“低”级别的 Python 时,问题对我来说可能不是那么微不足道。这似乎是不可能的。所以我想问一下,也许有人知道一些技巧xD。

编辑

到目前为止,消息中有一个提示要删除。需要一些时间来消化它,所以将它保留在这里:

@RobertGRZELKA 我想我自己得出的结论是,这根本无法完成。当您创建类的对象时,它会在内存中实例化一个新列表并引用它。因此,如果要引用另一个列表,则新对象没有意义。底线我相信您必须将引用作为类的属性,实现您的方法,然后覆盖您将要使用的列表方法,以便它们在引用列表上工作。当您阅读时告诉我,我将删除此答案 – Tomerikoo 2 小时前

标签: pythonlistclassinheritance

解决方案


尝试这个

class MyList(list):
     def __init__(self,value):
             self.extend(value)

我真的不明白为什么你会想要它,除非你想向列表对象添加更多方法。但这应该给你一个清单

t = [0, 1, 3, 100, 20, 4]
o = MyList(t)
o.sort()
t.sort()
assert(t==o)

推荐阅读