1

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)
Bhavish Agarwal
  • 663
  • 7
  • 13
  • 4
    It is not the structure of SO to ask multiple questions, it may be best that you ask your questions separately. That being said, your questions are those that are most easily answered by reading the documentation and learning Python before trying to use it. Why objects act as they do, or how class members work are all covered in the documentation. http://docs.python.org/2/tutorial/classes.html – Inbar Rose Apr 28 '13 at 12:16
  • 1
    possible duplicate of [what's the biggest difference between dir and \_\_dict\_\_ in python](http://stackoverflow.com/questions/14361256/whats-the-biggest-difference-between-dir-and-dict-in-python) – Aya Apr 28 '13 at 12:28
  • related: http://stackoverflow.com/questions/6761106/inspect-getmembers-vs-dict-items-vs-dir – Aya Apr 28 '13 at 12:28

1 Answers1

6

A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"]

From Data Model (Python Docs)

HennyH
  • 7,794
  • 2
  • 29
  • 39