AttributeError:“节点”对象没有属性“数据”

2024-10-01 04:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正处于学习Python的早期阶段。(免责声明,我在学校,这是一个家庭作业问题)。我正在尝试创建一个程序,根据婚礼宾客的姓名字母顺序,将他们分到房间的一侧。然而,当我运行我的程序时,我收到一条错误消息,上面写着“Traceback(最近一次调用last): 文件“C:\Python\Python36\Wedding Guests Program.py”,第29行,在 root.data.append(“M”)#M是字母表的一半。根据组的不同,这可能需要更改 AttributeError:“节点”对象没有属性“数据”

我联系了学校的一位家庭教师,但当他们在电脑上运行程序时,程序运行正常。我希望这里有人能给我指出我把事情搞砸的正确方向。这是我的密码:

class Node:
    def _init_ (self, left, right, data):
        self.left = None
        self.right = None
        self.data = list () #Using a list for people with the same first name
def addGuest (root, guest) : #Defining left requirements
    if guest < root.data [0] :
        if root.left == None:
            root.left = Node ()
            root.left.data.append (guest)
        else:
            addGuest (root.left, guest)
    else: #Defining right requirements
        if guest > root.data [0] :
            if root.right == None:
                root.right = Nide ()
                root.right.data.append (guest)
            else:
                addGuest (root.right, guest)
        else:
            root.right.data.append (guest)
def printGuest(root) :
    if root == None:
        return
    print(root.data)
    printGuest (root.left) #printing left and right so both sides of the room are represented.
    printGuest (root.right)
root = Node()
root.data.append("M") #M is halfway through the alphabet. Depending on the group, this may need to change
for i in range (0,8): #Choosing 8 to ensure it divides evenly. This can be changed
        addGuest (root, input("Add Guest"))
print ("Left side:")
printGuest (root.left)
print("Right Side:")
printGuest (root.right)

Tags: theself程序rightnonenodedataif
2条回答

问题是节点类_init_中的值应该是__init__。这意味着self.data = list()永远不会被分配。另外,创建列表的更具python风格的方法是self.data = []

在Node类中,确保在“init”构造函数(“init()”)和init())之前使用双下划线传递三个参数,要创建实例,您应该传递三个参数或设置它们的默认值。 根=节点() 到 根=节点(左,右,数据)#左,右,数据表示左,右,数据的值

否则,将出现以下错误: TypeErrorinit()缺少3个必需的位置参数:“left”、“right”和“data”

无论如何,您可以从参数列表中删除left、right,因为它在init()函数中没有任何用处

相关问题 更多 >