How can I make an instance of a class act like a dictionary?

John Salerno johnjsal at
Mon Feb 27 21:09:55 CET 2012

On Feb 27, 1:39 am, Chris Rebert <c... at> wrote:
> On Sun, Feb 26, 2012 at 11:24 PM, John Salerno <johnj... at> wrote:
> > Hi everyone. I created a custom class and had it inherit from the
> > "dict" class, and then I have an __init__ method like this:
> > def __init__(self):
> >        self = create()
> > The create function creates and returns a dictionary object. Needless
> > to say, this is not working. When I create an instance of the above
> > class, it is simply an empty dictionary rather than the populated
> > dictionary being created by the create function. Am I doing the
> > inheritance wrong, or am I getting the above syntax wrong by assigning
> > the return value to self?
> Assignment to `self` has no effect outside the method in question;
> Python uses call-by-object (
> ) for argument passing.
> Even in something like C++, I believe assignment to `this` doesn't work.
> > I know I could do self.variable = create() and that works fine, but I
> > thought it would be better (and cleaner) simply to use the instance
> > itself as the dictionary, rather than have to go through an instance
> > variable.
> Call the superclass (i.e. dict's) initializer (which you ought to be
> doing anyway):
>     super(YourClass, self).__init__(create())
> Cheers,
> Chris
> --

Thanks. This ended up working:

def __init__(self):
        self = super().__init__(create_board())

Is that what you meant for me to do? Why did assigning to self work in
this case, but not the original case?

More information about the Python-list mailing list