是否有一种自定义方法来实现对象克隆函数?

发布于 2025-02-12 12:05:59 字数 303 浏览 0 评论 0原文

我目前正在使用类似的东西:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦忆晨望 2025-02-19 12:05:59

在Python中这样做的标准化方法是呼叫者呼叫copy.copy.copy(obj)copy.deepcopy(obj)

Documentation in docs.python.org

作为标准将导致复制的对象具有引用原始对象。 deepcopy()将导致复制对象具有对这些对象的 copies 的引用。

说明:

class Example:
    def __init__(self, vals):
        self.vals = vals

import copy
orig = Example([1, 2, 3])
shallow = copy.copy(orig)
deep = copy.deepcopy(orig)
orig.vals.append('surprise')

print(f'orig.vals: {orig.vals}')
print(f'shallow.vals: {shallow.vals}')
print(f'deep.vals: {deep.vals}')

结果:

orig.vals: [1, 2, 3, 'surprise']
shallow.vals: [1, 2, 3, 'surprise']
deep.vals: [1, 2, 3]

请注意浅层和深副本之间的差异。 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) or copy.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:

class Example:
    def __init__(self, vals):
        self.vals = vals

import copy
orig = Example([1, 2, 3])
shallow = copy.copy(orig)
deep = copy.deepcopy(orig)
orig.vals.append('surprise')

print(f'orig.vals: {orig.vals}')
print(f'shallow.vals: {shallow.vals}')
print(f'deep.vals: {deep.vals}')

results in:

orig.vals: [1, 2, 3, 'surprise']
shallow.vals: [1, 2, 3, 'surprise']
deep.vals: [1, 2, 3]

Note the difference between the shallow and the deep copy. shallow.vals still pointed to the list in orig.vals, whereas deep.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文