113

I am really confused about the __dict__ attribute. I have searched a lot but still I am not sure about the output.

Could someone explain the use of this attribute from zero, in cases when it is used in a object, a class, or a function?

codeforester
  • 34,080
  • 14
  • 96
  • 122
Zakos
  • 2,100
  • 3
  • 15
  • 18
  • 3
    You should read this: http://docs.python.org/2/reference/datamodel.html – Henrik Andersson Nov 11 '13 at 13:23
  • 5
    No one's going to be able to alleviate your confusion if we don't understand what you're confused about. If you tried to explain that, then you might have an on topic question for the site. – Jon Clements Nov 11 '13 at 13:24
  • To avoid duplication, this question could be extended to asking how __dict__ conversion works. – Sajuuk May 10 '19 at 02:39

1 Answers1

114

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}
Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
  • 1
    Hi , if in the definition of func was the statement z=10 why in the output of func.__dict__ i see {} ? Lets say that the statement func.temp=1 next existed. – Zakos Nov 11 '13 at 13:39
  • 1
    @Zakos `__dict__` will hold attributes which describe the object. For a class, the variables inside it define the class but for a function, it is not. – thefourtheye Nov 11 '13 at 13:42
  • 2
    __dict__ will not print 'a' : 1 since it is not set in the __init__ method – rotemx Jan 14 '19 at 13:19
  • 4
    @rotemx We are not talking about member variables here. If you see the `print` statement, we are printing the `__dict__` of the class itself, not an instance of it. – thefourtheye Jan 16 '19 at 03:37
  • 2
    I tried this on a default data type in Python and it errored `AttribueError`, any reason for this. – Krishna Oza May 03 '20 at 05:32