gpt4 book ai didi

python - 为什么我会收到错误消息,指出我的类中不存在该属性?

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:24 25 4
gpt4 key购买 nike

我正在二分搜索树类中工作,当我运行插入方法时,出现此错误:

AttributeError: 'BSearch_tree' object has no attribute 'key'

我不明白我做错了什么,也不知道应该修复什么!

这是我的代码:

class Tree_node():
def __init__(self, key, val):
self.key = key
self.val = val
self.left = None
self.right = None

class BSearch_tree():
def __init__(self):
self.root=None

def insert(self, key, val):
if self.root is None:
self.root=Tree_node(key,val)
elif key == self.root.key:
self.val=val
elif key < self.root.key:
left = BSearch_tree()
left.root = self.root.left
self.root.left=BSearch_tree.insert(left,key,val)

elif key > self.root.key:
right = BSearch_tree()
right.root=self.root.right
self.root.right=BSearch_tree.insert(right,key,val)
return self

最佳答案

我希望我做对了;)

我建议不要担心 Tree_Node 而是像这样使用 BSearch_Tree :

import pprint

class BSearch_tree():
def __init__(self, key=None, val=None, root=None):
self.root = root
self.key = key
self.val = val
self.left = None
self.right = None

def insert(self, key, val):
if self.key is None:
self.root = self
self.key = key
self.val = val
elif key == self.key:
self.val=val
elif key < self.key:
if self.left == None:
self.left=BSearch_tree(key,val,self.root)
self.left.insert(key,val)
elif key > self.key:
if self.right == None:
self.right=BSearch_tree(key,val,self.root)
self.right.insert(key,val)
# return self

def __repr__(self):
return '<BSearch_tree: key: "%s", val: "%s", left: "%s", right: "%s" >' % self.key, self.val, self.left, self.right)

# lazy retrieval with recursion
def __getitem__(self, key):
if self.key is None:
raise KeyError
elif key == self.key:
return self.val
elif key < self.key:
if self.left == None:
raise KeyError
return self.left[key]

elif key > self.key:
if self.right == None:
raise KeyError
return self.right[key]

bt = BSearch_tree()
bt.insert(1,'1')
print bt[1]
bt.insert(2,'2')
print bt[2]
try:
print bt[3]
except KeyError:
print '3 not there as expected'

bt.insert(5,'5')
print bt[5]
bt.insert(3,'3')
print bt[3]
pprint.pprint(bt)

我有一种隐隐的感觉,我应该在某个地方使用 self.root,但我现在还不完全确定。

关于python - 为什么我会收到错误消息,指出我的类中不存在该属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23660424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com