Home > Net >  Couple of questions about how objects work in python
Couple of questions about how objects work in python

Time:12-22

class Node:
    def __init__(self, data = None):
        self.data = data
        self.next = None

node1 = Node (1)
node1.next = Node (2)

x = node1

When I say "x = node1", what exactly is x? As in is it a pointer to where node1 is stored or does it create a separate identical copy of the linked list? Or is it neither

I ask because if I were to add...

x = Node (100)

...node1 is not altered. But if I added...

x.data = 100

...instead, node1 would be altered in that the first value in the linked list would now be 100.

Also if I were to add...

print (node1)

...I'd get something like "<main.Node object at 0x0000019599685FD0>", is the 0x0000019599685FD0 part the memory address of the object?

CodePudding user response:

node1 = Node(1): node1 is a reference to the object created using Node(1).

The object's identifier is 0x0000019599685FD0 where in CPython (Python's default implementation) happens to be where the object is located.

x = node1 makes x refer to the same object in node1.

x.data = 100 changes attribute data of the object referenced by x.

x = Node (100) makes x reference a completely new object.

I highly suggest visualizing it using tools such as Python Tutor.

  • Related