Search code examples
pythonb-tree

Python B-tree: every node hangs from root


Ok, basically what I am trying to do is to have implemented a very basic and simple B-tree, but I am finding myself with a problem: the root node holds as a child every node in the tree. I have simplified as much as possible, and here is an example of the problem that I am facing:

>>> class Btree():
        subs = []
        value = 0


>>> a=Btree()
>>> b=Btree()
>>> c=Btree()
>>> a.value=1
>>> b.subs.append(a)
>>> b.value=2
>>> c.subs.append(b)
>>> c.value = 3
>>> c
<__main__.variable object at 0x103d916a0>
>>> c.value
3
>>> len(c.subs)
2
>>> c.subs
[<__main__.variable object at 0x103d91780>, <__main__.variable object at 0x103d917f0>]
>>> c.subs[1].value
2
>>> c.subs[0].value
1

Can somebody tell me what is going on?


Solution

  • You need to use an __init__() method to make instance attributes. The way you are doing it now you are declaring class attributes that are shared by all instances of the class. Try doing this instead:

    class BTree:
        def __init__(self):
            self.subs = []
            self.value = 0