Need help with simple OOP Python question

Peter Otten __peter__ at web.de
Mon Sep 5 03:10:14 EDT 2011


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
    # ...




More information about the Python-list mailing list