Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary Logic in Python class

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
{}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading