Channel72
Channel72

Reputation: 24739

Python: why is __dict__ attribute not in built-in class instances

If my understanding of the Python data model is correct, both classes and class instances have associated __dict__ objects which contain all the attributes. However, I'm a little confused as to why certain class instances, such as instances of str for example, don't have a __dict__ attribute.

If I create a custom class:

class Foo:
     def __init__(self):
             self.firstname = "John"
             self.lastname = "Smith"

Then I can get the instance variables by saying:

>>> f = Foo()
>>> print(f.__dict__)
{'lastname': 'Smith', 'firstname': 'John'}

But if I try to do the same with an instance of the built-in str, I get:

>>> s = "abc"
>>> print(s.__dict__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__dict__'

So, why don't instances of str have a __dict__ attribute?

Upvotes: 11

Views: 4379

Answers (2)

Makefile_dot_in
Makefile_dot_in

Reputation: 21

Just to add to this:

You can get the equivalent of a read only __dict__ using this:

{s:getattr(x, s) for s in dir(x)}

EDIT: Please note that this may contain more entries than __dict__. To avert this, you may use this as a workaround:

{s:getattr(x, s) for s in dir(x) if not s.startswith("__")}

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799370

Instances of types defined in C don't have a __dict__ attribute by default.

Upvotes: 14

Related Questions