Python 虽然我已经定义了函数,但代码有什么问题?

Python 虽然我已经定义了函数,但代码有什么问题?,python,python-3.6,Python,Python 3.6,这段代码给出了NameError,显示我没有定义函数,但我在类中实际定义了函数 我试了很多,但都解决不了 class Node(object): def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None def printList(se

这段代码给出了NameError,显示我没有定义函数,但我在类中实际定义了函数

我试了很多,但都解决不了

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList(object):
    def __init__(self):
        self.head = None

    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next

    def append(self, new_data):
        new_node = Node(new_data)
        if self.head is None:
            self.head = new_node
            return
        last = self.head
        while last.next:
            last = last.next
            last.next = new_node

    def merge(self, head1, head2):
        temp = None
        if head1 is None:
            return head2

        if head2 is None:
            return head1

        if head1.data <= head2.data:
            temp = head1
            temp.next = merge(head1.next, head2)

        else:
            temp = head2
            temp.next = merge(head1, head2.next)

        return temp

list1 = LinkedList()
list1.append(10)
list1.append(20)
list1.append(30)
list1.append(40)
list1.append(50)

list2 = LinkedList()
list2.append(5)
list2.append(15)
list2.append(18)
list2.append(35)
list2.append(60)

list3 = LinkedList()
list3.head = merge(list1.head, list2.head)

print("Merged Linked List is : ")
list3.printList()
您已将merge定义为LinkedList类的方法。这意味着您需要在类的实例上调用它,而不仅仅是它本身。例如,您可以替换合并。。。使用list3.merge…调用导致当前异常,并使用self.merge…调用方法内部的递归调用

但我不确定它是否需要是一个方法,因此可以将函数定义移出类并删除其自身参数。作为一个独立的函数,它可以很好地工作。

您需要创建一个。这是太多的代码。merge不是一个函数,它是一个应该从LinkedList实例调用的方法。
NameError                                 Traceback (most recent call last)
<ipython-input-11-22fca0a2d24d> in <module>()
     57 
     58 list3 = LinkedList()
---> 59 list3.head = merge(list1.head, list2.head)
     60 
     61 print("Merged Linked List is : ")

NameError: name 'merge' is not defined