复制对象时,是否可以保持身份相同?

时间:2019-05-13 13:26:00

标签: python

在类的__init__函数中,我初始化了一些变量,以使它们在我的类和其他类中可用。 这些变量将在以后的阶段中通过不同类的函数赋值。但是无论何时设置,它们的身份都会改变。由于我一直在传递这些变量的引用,因此我不希望它们的身份发生变化。

我已经尝试过copy.copy()copy.deepcopy(),但这也改变了变量的身份。

下面的代码以一种简单的方式描述了这种情况:

class MyObject:
    def __init__(self):
        self.name = 'test_object'
    def set_name(self, name):
        self.name = name

class MyClass:
    def __init__(self):
        self.my_object = MyObject()

def create_object():
    new_object = MyObject()
    new_object.set_name('new_object')
    print(f'Address of new object in function: {id(new_object)}')
    return new_object

if __name__ == '__main__':
    my_class = MyClass()

    print(f'Identity when variable has only be initialized: {id(my_class.my_object)}')

    my_class.my_object = create_object()

    print(f'Identity after the create has been called: {id(my_class.my_object)}')

上面的代码产生以下输出:

Identity when variable has only be initialized: 87379952
Address of new object in function: 87425104
Identity after the create has been called: 87425104

我想拥有的是my_class.my_object的身份保持不变,并且不会更改为在函数中创建的对象的身份。有人知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

您不必在初始化MyObject实例时创建MyClass的新实例,而是可以将引用显式传递给现有的MyObject实例:

class MyObject:
    def __init__(self):
        self.name = 'test_object'
    def set_name(self, name):
        self.name = name

class MyClass:
    def __init__(self, my_object):
        self.my_object = my_object

def create_object():
    new_object = MyObject()
    new_object.set_name('new_object')
    print('Address of new object in function:', id(new_object))
    return new_object

if __name__ == '__main__':
    my_object = create_object()

    print('Identity after the create has been called:', id(my_object))

    my_class = MyClass(my_object)

    print('Identity when my_class has been initialized:', id(my_class.my_object))

输出:

Address of new object in function: 140518937186936
Identity after the create has been called: 140518937186936
Identity when my_class has been initialized: 140518937186936