Need help with simple OOP Python question

srinivas hn hnsri49 at gmail.com
Mon Sep 5 11:34:22 CEST 2011


Hi,
You are getting same object because you are overriding the dictionary
update.
Its printing the proper value with the last updated instance of B.

If you want to see the two different instances of class B give print
self.sub inside the sub_add method in class A.

CHEERS
CNA
9986229891


On Mon, Sep 5, 2011 at 12:17 PM, Kristofer Tengström <krille012 at gmail.com>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()
>    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.
>
> Python version is 2.6.5 (I'm using Panda3D to create a 2½D game).
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110905/138debaf/attachment.html>


More information about the Python-list mailing list