Need help with simple OOP Python question

Kristofer Tengström krille012 at
Mon Sep 5 09:15:40 EDT 2011

Thanks everyone, moving the declaration to the class's __init__ method
did the trick. Now there's just one little problem left. I'm trying to
create a list that holds the parents for each instance in the
hierarchy. This is what my code looks like now:


class A:
    def __init__(self, parents=None):
        self.sub = dict()
        if parents:
            self.parents = parents
            self.parents = []
    def sub_add(self, cls):
        hierarchy = self.parents
        obj = cls(hierarchy)
        self.sub[] = obj

class B(A):
    id = 'inst'

base = A()

print vars(base)
print vars(base.sub['inst'])
print vars(base.sub['inst'].sub['inst'])


The output from this program is the following:

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794B8>}}

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794E0>}}

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {}}

As you can see, the problem looks similar to the one before: All the
instances have an identical parent list. However, I don't understand
why as self.parents is declared in the __init__ method. Any ideas?
What I want is for the first instance to have an empty list, the
second to have one element in the list and the third to have two
parent elements.

More information about the Python-list mailing list