class C(object):
def f(self):
print self.__dict__
print dir(self)
c = C()
c.f()
output:
{}
['__class__', '__delattr__','f',....]
why there is not a ‘f’ in self.__dict__
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
dir()does much more than look up__dict__First of all,
dir()is a API method that knows how to use attributes like__dict__to look up attributes of an object.Not all objects have a
__dict__attribute though. For example, if you were to add a__slots__attribute to your custom class, instances of that class won’t have a__dict__attribute, yetdir()can still list the available attributes on those instances:The same applies to many built-in types;
lists do not have a__dict__attribute, but you can still list all the attributes usingdir():What
dir()does with instancesPython instances have their own
__dict__, but so does their class:The
dir()method uses both these__dict__attributes, and the one onobjectto create a complete list of available attributes on the instance, the class, and on all ancestors of the class.When you set attributes on a class, instances see these too:
because the attribute is added to the class
__dict__:Note how the instance
__dict__is left empty. Attribute lookup on Python objects follows the hierarchy of objects from instance to type to parent classes to search for attributes.Only when you set attributes directly on the instance, will you see the attribute reflected in the
__dict__of the instance, while the class__dict__is left unchanged:TLDR; or the summary
dir()doesn’t just look up an object’s__dict__(which sometimes doesn’t even exist), it will use the object’s heritage (its class or type, and any superclasses, or parents, of that class or type) to give you a complete picture of all available attributes.An instance
__dict__is just the ‘local’ set of attributes on that instance, and does not contain every attribute available on the instance. Instead, you need to look at the class and the class’s inheritance tree too.