Introduction
So I'm trying to follow this tutorial on RealPython: link. I struggle to understand the part about defensive copying. I've replicated the source of my confusion in my own code below.
My question is – why is the IDs different in the a.lst_different_name is not a.lst_different_name
statement when using the same object (why does this statement evaluate to True
)? And why is the ID altered for the same object after invoking this comparison (see output)?
Code
class TestClass:
def __init__(self):
self.__lst = [1, 2, 3]
@property
def lst_different_name(self):
return self.__lst.copy()
a = TestClass()
print(a.lst_different_name)
print(id(a.lst_different_name))
print(id(a.lst_different_name))
print(a.lst_different_name is not a.lst_different_name)
print(id(a.lst_different_name))
Output
[1, 2, 3]
2462895845824
2462895845824
True
2462896109184