1

Here there is no attribute called "a" in the class Node then what is the meaning of x.a ? Can object name contain the character "." in python ?

class Node :
  def __init__(self, left = None, data = None, right = None) :
    self.left = left
    self.data = data
    self.right = right
x = Node(50)
x.a = Node(40)
  • You are simply mistaken about where attributes are allowed to be assigned. In Python, by default, an instance of a user-defined class can accept any attribute – juanpa.arrivillaga Apr 27 '21 at 03:06

1 Answers1

1

Python is a Dynamically Typed Language. Which means you can set the value of any variable without having to declare that variable.

In your code snippet, x = Node(50) is creating a new node class object with x.left assigned to 50.

Now by doing x.a = Node(40), we are just defining a new attribute of the object x with name a, which will be a Node class object with left value of 50.

If you do dir(x) it will give you something like this,

['__class__',
 '__delattr__',

  #Some other attributes
 
'__weakref__',
 'a',
 'data',
 'left',
 'right']

If you take a look at the last 4 attributes you can see that a is now also added as an attribute of the x object.

Conclution

if you do x.new_attribute = Node(10,20,30) when new_attribute isn't present in the object then python will just create a new attribute inside the x object with the name new_attribute & assign it the value of Node(10,20,30).

Jay Shukla
  • 454
  • 4
  • 13
  • Ok I understood. But what happens if I put x.a.b = Node(10). Will it be considered as (x.a).b or something else ? What happens if we keep on doing this x.a.b.c.d.e = Node(5) ? – VIMALAN S S Apr 27 '21 at 05:53
  • x.n.m is possible as long as x.n is a class object. x.a.b.c.d.e will work if x.a.b.c.d is object of some class. This will not work if the parent element is an non-class object, lets say integer. If x.p.q = 25 then x.p.q.r will give error. – Jay Shukla Apr 27 '21 at 22:44