1

I created 2 class instances(stack0, stack1) from a class Stack There is a class variable named in class Stack, which has the other stack address(reference), ie) stack0.other_stack is stack1 and stack1.other_stack is stack0. but It doesn't work as I expected though I used deepcopy function.

I tried making a class function that deepcopies the other_stack.

stack0 = Stack(stack_list, arr_size//2, 0)
stack1 = Stack(stack_list, arr_size//2, 1)
stack0.other_stack = deepcopy(stack1)
stack1.other_stack = deepcopy(stack0)
print(stack0.other_stack is stack1)
print(id(stack0.other_stack), id(stack1))

print(stack0.other_stack is stack1) prints: False

print(id(stack0.other_stack), id(stack1)) prints: 4328836344 4328835224

I expected stack0.other_stack is the exactly same as stack1 and vice-versa.

1 Answer 1

2

The is keyword checks if the identity of two values is the same, which is implemented through the memory address. Making a (deep)copy will create a copy in a new memory address, which is why stack1 is deepcopy(stack1) returns False.

Sign up to request clarification or add additional context in comments.

2 Comments

so how can I make them have same memory address? I want to modify different stack in other stack's class function.
To achieve this you can assign the other_stack as stack0.other_stack = stack1. This will copy stack1 by reference, so stack0.other_stack will point to stack1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.