class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
print a.x, a.y
b = attrdict()
b.x, b.y = 1, 2
print b.x, b.y
Could somebody explain the first four lines in words? I read about classes and methods. But here it seems very confusing.
My shot at a line-by-line explanation:
This line declares a class attrdict as a subclass of the built-in dict class.
This is your standard
__init__
method. The call todict.__init__(...)
is to utilize the super class' (in this case, dict) constructor (__init__
) method.The final line,
self.__dict__ = self
makes it so the keyword-arguments (kwargs) you pass to the__init__
method can be accessed like attributes, i.e., a.x, a.y in the code below.Hope this helps clear up your confusion.
Here's a good article that explains
__dict__
:The Dynamic dict
The
attrdict
class exploits that by inheriting from a dictionary and then setting the object's__dict__
to that dictionary. So any attribute access occurs against the parent dictionary (i.e. thedict
class it inherits from).The rest of the article is quite good too for understanding Python objects:
Python Attributes and Methods
You are not using positional arguments in your example. So the relevant code is:
In the first line you define class
attrdict
as a subclass ofdict
. In the second line you define the function that automatically will initialize your instance. You pass keyword arguments (**kargs
) to this function. When you instantiatea
:you are actually calling
dict instance core initialization is done by initializing the
dict
builtin superclass. This is done in the third line passing the parameters received inattrdict.__init__
. Thus,makes
self
(the instancea
) a dictionary:The nice thing occurs in the last line: Each instance has a dictionary holding its attributes. This is
self.__dict__
(i.e.a.__dict__
).For example, if
we could write
a.x
ora.y
and get values 1 or 2, respectively.So, this is what line 4 does:
is equivalent to:
Then I can call
a.x
anda.y
.Hope is not too messy.