0

I have the following Python code. I was expecting the dictionary of the object node1 to have values 'a','b' and the dictionary of object node2 to have values 'c','d'. But am getting the output - ([['a'], ['b'], ['c'], ['d']]) - in both the cases. Why is it that the dictionaries of two distinct objects (node1 and node2) acting as if there is only one single dictionary?

class Node:
    Dictionary={}

def main():

    node1 = Node()
    node2 = Node()
    node1.Dictionary.setdefault(1, []).append('a')
    node1.Dictionary.setdefault(2, []).append('b')
    node2.Dictionary.setdefault(3, []).append('c')
    node2.Dictionary.setdefault(4, []).append('d')
    print("Node 1 ",node1.Dictionary.values())
    print("Node 2 ",node2.Dictionary.values())

main()
Krishn Nand
  • 135
  • 1
  • 1
  • 9
  • https://stackoverflow.com/questions/8959097/what-is-the-difference-between-class-and-instance-variables – MCMZL Jan 12 '18 at 12:28
  • _instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class_ https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables – srikavineehari Jan 12 '18 at 12:37
  • 1
    `Dictionary={} # Shared by all instances` – srikavineehari Jan 12 '18 at 12:38
  • Thanks a lot for the information. Helped me in getting a better understanding of Python. Having been into OOP, i thought Python would behave the same way as the rest of languages. – Krishn Nand Jan 12 '18 at 13:18

0 Answers0