是否有一种自定义方法来实现对象克隆函数?
我目前正在使用类似的东西:
class MyClass:
def __init__(self, myVar):
self.myVar = myVar
def clone(self):
return MyClass(self.myVar)
在Python中是否有更多的自定义(标准)方式,也许是通过覆盖操作员__新__
或类似的东西?
我宁愿这个功能是实例函数,而不是类(静态)函数,但是我很高兴听到任何建议。
感谢您的帮助。
I am currently using something like this:
class MyClass:
def __init__(self, myVar):
self.myVar = myVar
def clone(self):
return MyClass(self.myVar)
Is there a more custom (standard) way of doing this in Python, perhaps by overriding operator __new__
or something of that sort?
I'd rather this function to be an instance function and not a class (static) function, but I'd be happy to hear any suggestion.
Thanks for helping out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Python中这样做的标准化方法是呼叫者呼叫
copy.copy.copy(obj)
或copy.deepcopy(obj)
。Documentation in docs.python.org
作为标准将导致复制的对象具有引用原始对象。
deepcopy()
将导致复制对象具有对这些对象的 copies 的引用。说明:
结果:
请注意浅层和深副本之间的差异。
shallow.vals
仍然指向orig.vals
的列表,而deep.vals
是该列表的独立副本。现在,对于您的示例课,这就是所需的一切:您不需要在课程中添加特殊方法。但是,如果您想要更自定义的克隆行为,则可以实现
__ copy __
和/或__ DeepCopy __
您的课程中的方法。A standardised way of doing this in Python is for the caller to call
copy.copy(obj)
orcopy.deepcopy(obj)
.Documentation at docs.python.org
As standard,
copy()
will result in the copied object having references to the same objects that the original did.deepcopy()
will result in the copied object having references to copies of those objects.To illustrate:
results in:
Note the difference between the shallow and the deep copy.
shallow.vals
still pointed to the list inorig.vals
, whereasdeep.vals
was an independent copy of that list.Now, for your example class, this is all that is needed: you don't need to add a special method to your class. But if you wanted cloning behaviour that was more custom, you could implement the
__copy__
and/or__deepcopy__
methods in your class.