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([0, 1, 3, 4])在MyList中就地执行某些操作时无法解决问题。


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小时前

试试这个

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)

最新更新