gpt4 book ai didi

python - 名称错误 : name "AnyName" is not defined

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

我正在尝试做一个基于链表和节点的 N 叉树。但是每当我尝试向树添加新值时,我都会得到:

NameError:未定义名称“self”

我使用模块,所以我必须从其他文件导入类。

我在 def addTree(self, value, parent = self.root): Tree 代码中得到了这个错误

树代码

from Resources.LinkedList import *

class Tree:
def __init__(self):
self.root = LinkedList()

def addTree(self, value, parent = self.root):
parent.addLinkedList(value)

节点代码

from Resources.LinkedList import *

class Node:
def __init__(self,name):
self.name = name
self.children = LinkedList()
self.next = None

链表代码

from Resources.Node import *
from Resources.Compare import *

class LinkedList:
def __init__(self):
self.first = None

def addLinkedList(self,value):
if (not self.first):
self.first = Node(value)
else:
compare = Compare()
if(compare.compare(self.first,value)>0):
stack = self.first
self.first = Node(value)
self.first.next = stack
return True
else:
previous = self.first
current = self.first.next

while(current):
if (compare.compare(current,value)<0):
previous = current
current = current.next
return True
elif (compare.compare(current,value)>0):
stack = current
previous.next = Node(value)
previous.next.next = stack
return True
else:
previous.next = Node(value)
previous.next.next = current.next
return True

previous.next = Node(value)
return True

也感谢您的帮助,我是 Python 的新手,我不知道自己做错了什么。

最佳答案

问题是“self”只在方法中定义,不能在参数中使用,在这些情况下的技巧是使用 None 作为参数并进行验证:

def addTree(self, value, parent = None):
if parent is None:
parent = self.root
parent.addLinkedList(value)

关于python - 名称错误 : name "AnyName" is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485751/

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