Reputation: 57421
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.
Upvotes: 25
Views: 19654
Reputation: 48067
As per Python Document, object.__dict__
is:
A dictionary or other mapping object used to store an object’s (writable) attributes.
Below is the sample example:
>>> class TestClass(object):
... def __init__(self):
... self.a = 5
... self.b = 'xyz'
...
>>> test = TestClass()
>>> test.__dict__
{'a': 5, 'b': 'xyz'}
Upvotes: 12
Reputation: 42748
Assigning the dictionary self
to __dict__
allows attribute access and item access:
>>> c = Config()
>>> c.abc = 4
>>> c['abc']
4
Upvotes: 17