Skip to content
Advertisement

How is the initialization of objects considered in this code?

In this class there is no attribute called “a” then how x.a is considered ? Similarly what is “x.a.b”, “x.a.b.c”, “x.a.b.c.d”, “x.a.b.c.d.e” and how are they considered ?Is b is an attribute of x.a in the case of “x.a.b” and c is a attribute of x.a.b in the case of “x.a.b.c” ? Explain breifly !!! I am totally confused 😵

class Node :
  def __init__(self, data = None, next = None) :
    self.data = data
    self.next = next
x = Node(50)
x.a = Node(40)
x.a.b = Node(30)
x.a.b.c = Node(20)
x.a.b.c.d = Node(10)
x.a.b.c.d.e = Node(5)
print(x.a.b.c.d.e.data)

Advertisement

Answer

I suppose that similar to the declaration of the first variable x, x.a is an implicit initialization of that variable. x doesn’t exists until you initialize it, so does x.a.

So by initializing x.a you first need x to exists, that mean you cannot do something like

class Node :
  def __init__(self, data = None, next = None) :
    self.data = data
    self.next = next
x = Node(50)
x.a = Node(40)
# Then try to create the chain until C without creating first b
x.a.b.c = Node(20)

If you test it out it will point

Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: 'Node' object has no attribute 'b'

So in short. I think that even though the Node class has no attributes, the chain is just creating child nodes to the first variable.

x 
|_ Node() -> self, data, next
|_ a _
     |_ Node () -> self, data, next
     |_ b _
          |_ Node () -> self, data, next
          |_ c _ 
               |_ ...

Notice that as mentioned by quamrana, only a is directly attached to x.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement