小编Sim*_*ans的帖子

实现复制方法的最佳实践

copy在类中实现该方法的最佳实践是什么?

这是我班级的一个例子:

class MyClass:
    def __init__(self, foo, bar=None):
        self.foo = foo
        if bar is not None:
            self.bar = bar
        else:
            self.bar = {'Hello': 'Ciao'}
Run Code Online (Sandbox Code Playgroud)

我发现五年前的帖子提示了以下方式:

import copy

def copy(self):
    return MyClass(copy.copy(self.foo), copy.copy(self.bar))
Run Code Online (Sandbox Code Playgroud)

它仍然是唯一的方法,还是有其他可能性?

我需要创建一个对象的副本,以避免函数更改原始对象.功能是这样的:

def translate_and_print(my_class, dict={'Hello':'Ciao'}):
    temp = my_class # here I want to use the copy method: temp = my_class.copy()
    temp.foo = temp.bar[temp.foo]
    print(temp.foo)
Run Code Online (Sandbox Code Playgroud)

以下代码的输出是"Ciao"​​,"Ciao"​​但应该是"Ciao"​​,"Hello"

mc = MyClass('Hello')
translate_and_print(mc)
print(mc.foo)
Run Code Online (Sandbox Code Playgroud)

如果我使用该copy()方法,我有错误:

AttributeError:'MyClass'对象没有属性'copy'

python

7
推荐指数
3
解决办法
4117
查看次数

标签 统计

python ×1