I was clear how dictionaries work in Python until I found this logic.
class Sample:
__test = {}
def __init__(self):
self.__dict__ = self.__test
self.key = "answer"
self.count = "numbers"
def print_test(self):
print(self.__test)
s = Sample()
s.print_test()
In the above code a dictionary is initialized and then same variable is assigned to the class dict. In the next line we are initializing 2 more variables to the class.
In the end we are initializing Sample class to an "s object"
As per my understanding this should be following output and __test dictionary should be empty
s.count = "numbers"
s.key = "answers"
But to my surprise the print_test functions returns
{'count': 'numbers', 'key': 'answer'}
Can anyone explain how the __test dictionary got these items as key value pairs.
>Solution :
The __init__ function runs sequentially. When you set self.__dict__ = self.__test, you assign the object’s internal state dictionary to be empty. However, when you next set the values of self.key and self.count, those attributes are added to the now empty self.__dict__, and by mutual assignment, to self.__test
You can see the difference you assign the empty dict at the end of the __init__ method.
class Sample:
__test = {}
def __init__(self):
self.key = "answer"
self.count = "numbers"
self.__dict__ = self.__test
def print_test(self):
print(self.__test)
s = Sample()
s.print_test()
# prints:
{}