Note that not all objects have a __dict__
attribute, and moreover, sometimes calling dict(a)
where the object a
can actually be interpreted as a dictionary will result in a sensible conversion of a
to a native python dictionary. For example, with numpy arrays:
In [41]: a = np.array([[1, 2], [3, 4]])
In [42]: dict(a)
Out[42]: {1: 2, 3: 4}
But a
does not have an attribute 1
whose value is 2
. Instead, you can use hasattr
and getattr
to dynamically check for an object's attributes:
In [43]: hasattr(a, '__dict__')
Out[43]: False
In [44]: hasattr(a, 'sum')
Out[44]: True
In [45]: getattr(a, 'sum')
Out[45]: <function ndarray.sum>
So, a
does not have __dict__
as an attribute, but it does have sum
as an attribute, and a.sum
is getattr(a, 'sum')
.
If you want to see all the attributes that a
has, you can use dir
:
In [47]: dir(a)[:5]
Out[47]: ['T', '__abs__', '__add__', '__and__', '__array__']
(I only showed the first 5 attributes since numpy arrays have lots.)