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


Groups > comp.lang.python > #12760

Re: Need help with simple OOP Python question

From Peter Otten <__peter__@web.de>
Subject Re: Need help with simple OOP Python question
Date 2011-09-05 09:10 +0200
Organization None
References <dce02da0-c9c9-4331-aa2e-7d99f5e26cd1@g9g2000yqb.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.767.1315206626.27778.python-list@python.org> (permalink)

Show all headers | View raw


Kristofer Tengström wrote:

> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables. The code looks like this:
> 
> ---------------------------------------------
> 
> class A:
>     sub = dict()

Putting it into the class like this means sub is shared by all instances.

>     def sub_add(self, cls):
>         obj = cls()
>         self.sub[obj.id] = obj
> 
> class B(A):
>     id = 'inst'
> 
> base = A()
> base.sub_add(B)
> base.sub['inst'].sub_add(B)
> 
> print # prints a blank line
> print base.sub['inst']
> print base.sub['inst'].sub['inst']
> 
> ----------------------------------------------
> 
> Now, what I get from this is the following:
> <__main__.B instance at 0x01FC20A8>
> <__main__.B instance at 0x01FC20A8>
> Why is this? What I want is for them to be two separate objects, but
> it seems like they are the same one. I've tried very hard to get this
> to work, but as I've been unsuccessful I would really appreciate some
> comments on this. I'm sure it's something really easy that I just
> haven't thought of.

Your class A needs an initialiser:

class A:
    def __init__(self):
        self.sub = {} # one dict per instance
    # ...

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


Thread

Need help with simple OOP Python question Kristofer Tengström <krille012@gmail.com> - 2011-09-04 23:47 -0700
  Re: Need help with simple OOP Python question Stephen Hansen <me+list/python@ixokai.io> - 2011-09-05 00:07 -0700
  Re: Need help with simple OOP Python question Peter Otten <__peter__@web.de> - 2011-09-05 09:10 +0200
  Re: Need help with simple OOP Python question Ben Finney <ben+python@benfinney.id.au> - 2011-09-05 17:26 +1000
    Re: Need help with simple OOP Python question Kristofer Tengström <krille012@gmail.com> - 2011-09-05 06:15 -0700
      Re: Need help with simple OOP Python question Peter Otten <__peter__@web.de> - 2011-09-05 16:43 +0200
        Re: Need help with simple OOP Python question Jon Clements <joncle@googlemail.com> - 2011-09-05 07:59 -0700
          Re: Need help with simple OOP Python question Peter Otten <__peter__@web.de> - 2011-09-05 17:28 +0200
      Re: Need help with simple OOP Python question Terry Reedy <tjreedy@udel.edu> - 2011-09-05 13:38 -0400
        Re: Need help with simple OOP Python question Piet van Oostrum <piet@vanoostrum.org> - 2011-09-08 12:53 +0200

csiph-web