Need help with simple OOP Python question

Kristofer Tengström krille012 at gmail.com
Mon Sep 5 15:15:40 CEST 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
        else:
            self.parents = []
    def sub_add(self, cls):
        hierarchy = self.parents
        hierarchy.append(self)
        obj = cls(hierarchy)
        self.sub[obj.id] = obj

class B(A):
    id = 'inst'

base = A()
base.sub_add(B)
base.sub['inst'].sub_add(B)

print
print vars(base)
print
print vars(base.sub['inst'])
print
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