[Tutor] putting instance variables into a dict

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 30 01:00:28 CET 2006



On Mon, 30 Jan 2006, Shuying Wang wrote:

> So I've got a class X with instance variables a, b, c. Is there any way
> of creating a dictionary of these instance variables besides the
> no-brainer way of doing dictionary = {'a' : X.a, 'b' : X.b, 'c' : X.c} ?

Hi Shuying,

It's an somewhat low-level detail that the attributes of a class instance
can be accessed through a special __dict__ object:

######
>>> class SomeClass:
...     def __init__(self, n):
...         self.n = n
...     def add(self, x):
...         return self.n + x
...
>>> s = SomeClass(5)
>>> s.__dict__
{'n': 5}
######


Does this apply to your question?


Classes can also be extended so that, to the untrained eye, they look very
much like dictionaries.  See:

    http://www.python.org/doc/ref/sequence-types.html

for some details about having objects implement Python's container
protocol.


Best of wishes!



More information about the Tutor mailing list