Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20926

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

References <a48bde30-31ed-45a9-ba89-6559c17d0992@y17g2000yqg.googlegroups.com>
Date 2012-02-26 23:39 -0800
Subject Re: How can I make an instance of a class act like a dictionary?
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.190.1330328350.3037.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Feb 26, 2012 at 11:24 PM, John Salerno <johnjsal@gmail.com> 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 (http://effbot.org/zone/call-by-object.htm
) 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
--
http://rebertia.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How can I make an instance of a class act like a dictionary? John Salerno <johnjsal@gmail.com> - 2012-02-26 23:24 -0800
  Re: How can I make an instance of a class act like a dictionary? Chris Rebert <clp2@rebertia.com> - 2012-02-26 23:39 -0800
    Re: How can I make an instance of a class act like a dictionary? John Salerno <johnjsal@gmail.com> - 2012-02-27 12:09 -0800
      Re: How can I make an instance of a class act like a dictionary? Benjamin Kaplan <benjamin.kaplan@case.edu> - 2012-02-27 15:37 -0500
  Re: How can I make an instance of a class act like a dictionary? Dan Sommers <dan@tombstonezero.net> - 2012-02-27 10:52 +0000

csiph-web