在 python 考试中得到了这个练习。 尝试返回一个像这样的列表的深拷贝:
l = list()
l = [0,1,2]
l1 = l
l[0] = 1
l1 应该包含 [0,1,2]
而不是 [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 中的 '='
是一个语句而不是运算符,它不能被覆盖。关于如何返回作业的深拷贝的任何想法?已经尝试了很多但没有成功。
最佳答案
据我所知,如果不使用某种额外的语法,这在 python 中是不可能的。正如您所说,您不能覆盖 =
。
关于分配列表的 Python 深层复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433573/