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?
Instances of types defined in C don't have a __dict__ attribute by default.
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("__")}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With