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.
You are not using positional arguments in your example. So the relevant code is:
In the first line you define class
attrdictas 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
dictbuiltin 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.xora.yand get values 1 or 2, respectively.So, this is what line 4 does:
is equivalent to:
Then I can call
a.xanda.y.Hope is not too messy.