I am trying to understand the bunch pattern in python, which I believe can be expressed in the following way:
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
usage:
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)
I understand what update does on a dict:
dict1.update(dict2)
will add the content of dict2(name:value pairs) to dict1. Here comes my questions:
What is "__dict__"? Why is it not shown in the dir of the object while it is shown in hasattr()? for example:
>>> class test:
def __init__(self, a):
self.a = a
>>> t = test(10)
>>> t.__dict__
{'a': 10}
>>> hasattr(t, "a")
True
>>> hasattr(t, "__dict__")
True
>>> dir(t)
['__doc__', '__init__', '__module__', 'a']
>>>
And finally, how am I able to access the attribute 'name' in the bunch class with a dot operator?
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)