In the __init__ function of a class I initialize some variables in order to make them available throughout my class and other classes. These variables are given a value at a later stage in a function of a different class. But whenever they are set their identity changes. Since I have been passing around the references to these variables I don't want their identity to change.

I have already tried copy.copy() and copy.deepcopy(), but this also changes the identity of the variables.

The code below describes the situation in a simple way:

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)}')

The code above produces the following output:

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

What I would like to have is that the identity of my_class.my_object stays the same and does not change to the identity of the object created in the function. Would someone know how to achieve this?

1 Answers

0
mkrieger1 On

Instead of creating a new instance of MyObject when initializing an instance of MyClass, you can explicitly pass a reference to an existing MyObject instance:

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))

Output:

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