4

Possible Duplicate:
inspect.getmembers() vs __dict__.items() vs dir()

class Base():
    def __init__(self, conf):
        self.__conf__ = conf
        for i in self.__dict__:
            print i,"dict"
        for i in dir(self):
            print i,"dir"

class Test(Base):
      a = 1
      b = 2

t = Test("conf")

The output is:

__conf__ dict
__conf__ dir
__doc__ dir
__init__ dir
__module__ dir
a dir
b dir

Can anyone explain a little bit about this?

Community
  • 1
  • 1
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 1
    I'm not sure how you're getting that output. Where is the `dict` and `dir` coming from? – kindall Nov 09 '12 at 06:03
  • @kindall I just fixed the code, `print i,"dict"` and `print i, "dir"` – Hanfei Sun Nov 09 '12 at 06:06
  • As far as I know, `__conf__` has no special meaning in python. You shouldn't use variable (or attribute) names `__something__` unless you're using it for the special meaning assigned by the python standard because those variables are *reserved* for future versions of python. – mgilson Nov 09 '12 at 06:21
  • 1
    another useful function in the family is `vars`. When faced with a `class` I haven't seen before, I use both `dir(t)` and `vars(t)` to sound it out. – Williams Nov 09 '12 at 07:07
  • Please [search](http://stackoverflow.com/search?q=[python]+%2Bdir+%2B__dict__+%2Bdifference&submit=search) before asking – Piotr Dobrogost Nov 09 '12 at 08:43

1 Answers1

9

An object's __dict__ stores the attributes of the instance. The only attribute of your instance is __conf__ since it's the only one set in your __init__() method. dir() returns a list of names of "interesting" attributes of the instance, its class, and its parent classes. These include a and b from your Test class and __init__ from your Base class, plus a few other attributes Python adds automatically.

Class attributes are stored in each class's __dict__, so what dir() is doing is walking the inheritance hierarchy and collecting information from each class.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Good answer, especially the first part. See [this answer](http://stackoverflow.com/questions/14361256/whats-the-biggest-difference-between-dir-and-dict-in-python/14361362#14361362) for a detailed explanation of the "interesting attributes of the instance". – Peterino Feb 26 '17 at 16:39