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.
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.
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.
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.
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.
Assigning the dictionary self
to __dict__
allows attribute access and item access:
>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With