[英]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. 好的,基本上我想做的是实现一个非常基本且简单的B树,但是我发现自己遇到了一个问题:根节点将孩子作为树中的每个节点。 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? 有人可以告诉我发生了什么吗?
You need to use an __init__()
method to make instance attributes. 您需要使用
__init__()
方法创建实例属性。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.