分配时列表的 Python 深度复制
在 python 考试中得到了这个练习。 尝试返回一个列表的深层副本,如下所示:
l = list()
l = [0,1,2]
l1 = l
l[0] = 1
l1 should contains [0,1,2]
not [1,1,2]
指定要实现的练习通过使用元类来实现。
class deep(type):
def __new__(meta, classname, bases, classDict):
return type.__new__(meta, classname, bases, classDict)
def __init__(cls, name, bases, dct):
super(deep, cls).__init__(name, bases, dct)
def __call__(cls, *args, **kwds):
return type.__call__(cls, *args, **kwds)
class list(metaclass=deep):
def __init__(self):
pass
据我所知,python中的'='
是一个语句而不是一个运算符,它不能被覆盖。关于如何在作业中返回深层副本有什么想法吗?已经尝试了很多但没有成功。
Got this exercise on a python exam.
Trying to return a deep o copy of a list like this:
l = list()
l = [0,1,2]
l1 = l
l[0] = 1
l1 should contain [0,1,2]
not [1,1,2]
The exercise specified to implement it by using a metaclass.
class deep(type):
def __new__(meta, classname, bases, classDict):
return type.__new__(meta, classname, bases, classDict)
def __init__(cls, name, bases, dct):
super(deep, cls).__init__(name, bases, dct)
def __call__(cls, *args, **kwds):
return type.__call__(cls, *args, **kwds)
class list(metaclass=deep):
def __init__(self):
pass
From what i know , the '='
in python is a statement and not an operator and it can't be overriden. Any idea on how to return a deep copy on assignment? Have been trying quite a lot but with no success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,如果不使用某种额外的语法,这在 python 中是不可能的。正如您所说,您无法覆盖
=
。As far as I'm aware, this is not possible in python without using some kind of extra syntax. As you said, you can't override
=
.要了解
l1 = l
在 Python 中的作用,请阅读 其他语言有“变量”,Python有“名称”。要更改
l[0] = 1
的功能,您可以重写l
的__setitem__()
方法:要更改
l = 的内容列表(); l = [0,1,2]
您可以在 CPython 中定义List.__del__()
方法并操作l
所属的命名空间,例如使用 <代码>检查模块。不用说,你永远不应该这样做。To understand what
l1 = l
does in Python read Other languages have "variables", Python has "names".To change what
l[0] = 1
does you could overridel
's__setitem__()
method:To change what
l = List(); l = [0,1,2]
does you could defineList.__del__()
method in CPython and manipulate the namespacel
belongs to e.g., usinginspect
module. Needless to say you should never do that.