Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between dir(self) and self.__dict__ [duplicate]

Tags:

python

class

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?

like image 847
Hanfei Sun Avatar asked Feb 19 '23 13:02

Hanfei Sun


1 Answers

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.

like image 153
kindall Avatar answered Mar 18 '23 02:03

kindall