+ 1
How come 1st and 3rd object heap address r coming same? !! Python programming doubt please help
Class Test: def __init__(self,data): self.data = data print(self.data) obj = Test(5) print(obj) obj = Test(6) print(obj) obj = Test(7) print(obj)
7 Respostas
+ 6
https://stackoverflow.com/questions/40514829
Read example 3 about Alternating Memory Allocation
+ 5
Martin Taylor there can be more than 2 Test() objects with different memory heaps, they just can't have the same variable name
+ 4
Because, when you re-assigned 'obj' to 'Test(6)', the initial value of 'obj' that is Test(5) was dropped and thus the memory location was freed. So python re-used the location when you assigned 'obj' to Test(7).
Try adding another line to the code
obj = Test(8)
print(obj)
You will find that this is the same location as the second one. This is because python re-uses memory that has been previously used.
The reason the memory location is alternating and not continuous is because when you re-assign, the memory location is still in use and freed after the assigning. So it is used when you re-assign a second time.
0
# A single node of a singly linked list
class Node:
# constructor
def __init__(self, data = None, next=None):
self.data = data
self.next = next
# A Linked List class with a single head node
class LinkedList:
def __init__(self):
self.head = None
# insertion method for the linked list
def insert(self, data):
newNode = Node(data)
if(self.head):
current = self.head
while(current.next):
current = current.next
current.next = newNode
else:
self.head = newNode
# print method for the linked list
def printLL(self):
current = self.head
while(current):
print(current.data)
current = current.next
# Singly Linked List with insertion and print methods
LL = LinkedList()
LL.insert(3)
LL.insert(4)
LL.insert(5)
LL.printLL()
Then how come in insert method newNode object's heap address is not coming alternatively on each insertion method call.