Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 218
Channel72 Avatar asked Feb 29 '12 15:02

Channel72


2 Answers

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

like image 63
Ignacio Vazquez-Abrams Avatar answered Sep 30 '22 05:09

Ignacio Vazquez-Abrams


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("__")}
like image 44
Makefile_dot_in Avatar answered Sep 30 '22 06:09

Makefile_dot_in