Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of self.__dict__ = self in a class definition

Tags:

I'm trying to understand the following snippet of code:

class Config(dict):
    def __init__(self):
        self.__dict__ = self

What is the purpose of the line self.__dict__ = self? I suppose it overrides the default __dict__ function with something that simply returns the object itself, but since Config inherits from dict I haven't been able to find any difference with the default behavior.

like image 845
Kurt Peek Avatar asked Oct 03 '16 13:10

Kurt Peek


People also ask

What is self __ dict __ in python?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects.

What does self __ class __ do?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

What is __ slots __ in python?

slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects. As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM.

What is dict attribute python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.


1 Answers

Assigning the dictionary self to __dict__ allows attribute access and item access:

>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
like image 76
Daniel Avatar answered Oct 23 '22 10:10

Daniel