[Tutor] dictionaries in classes

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Oct 14 22:01:19 CEST 2005



On Fri, 14 Oct 2005, Luke Jordan wrote:

>  I'm trying to have functions to create, edit and store dictionaries
>  within a class.

Here's a small example of a class:

######
class Person:
    def __init__(self, name):
        self.name = name
######


Let's try pickling an instance of it:

######
>>> p = Person("Luke")
>>> pickle.dumps(p)
"(i__main__\nPerson\np0\n(dp1\nS'name'\np2\nS'Luke'\np3\nsb."
######


Given a string like that, let's see if we can unpickle it back to an
object instance:

######
>>> p2 =
pickle.loads("(i__main__\nPerson\np0\n(dp1\nS'name'\np2\nS'Luke'\np3\nsb.")
>>> p2
<__main__.Person instance at 0x4048d8cc>
>>> p2.name
'Luke'
######


> I don't know why I can't figure out how to make the dictionary an
> attribute of the class, or if that's even possible.

You may want to make it an attribute of the class instance, and not
necessarily one of the class itself.  A class attribute is shared among
all instances, and that's probably not what you want.  The example above
shows how to initialize an attribute of a class instance, and that's
probably what you've been missing.


If you have more questions, please feel free to ask!



More information about the Tutor mailing list