Getting to Know the .__dict__ Attribute
00:00
To understand what the .__dict__
attribute is, you need to remember that everything in Python is an object, and objects can have attributes and methods or data and behaviors.
00:13
And the .__dict__
attribute is one of those attributes, but it’s a special one. So it’s an attribute of Python objects, for example, classes, but not just of classes, as you’ll see in a minute.
00:27
Now, this .__dict__
attribute represents a namespace. Now, what does a namespace do? A namespace maps the attribute names to the values of the attributes, and it maps the method names to the method objects.
00:43
So maybe unsurprisingly, given the name of the .__dict__
attribute, it’s a dictionary. And the keys of that dictionary are the names of attributes and methods, and the values are the values of the attributes and the method objects.
01:01
Now, the cool thing is these dunder attributes are recognized and used internally by the interpreter to process classes and objects. But that doesn’t stop me, and it shouldn’t stop you from lifting the hood and snooping around just a little bit, just looking, not touching, not yet anyway. So where can you find this .__dict__
attribute?
01:28 Well, you can find it in user-defined classes and their instances, and you will see some examples later in the course. But not just classes. You can also see it in modules in user-defined functions and methods.
01:42
And in the written tutorial on which this video course is based, there’s a really cool example of how you can add an attribute to a function. Yes, you’ve heard that right. Functions can have attributes, and you can create those using the .__dict__
attribute.
01:59
You can also find this .__dict__
attribute in built-in exceptions and their instances, in classes created with the built-in type()
function, and in built-in data types.
02:13
But not all objects have a .__dict__
attribute. Whereas built-in data types have them, instances of built-in data types do not, neither do built-in functions nor objects with a .__slots__
attribute.
02:30 Now, the how and why of that is beyond the scope of this course, but I invite you to do your own research here.
02:39
So now you know what the .__dict__
attribute is and what it’s used for. You are ready to create a demo class in the next lesson and to inspect its .__dict__
attribute.
Become a Member to join the conversation.