Функция класса не находит позиционный аргумент Self в Python - PullRequest
0 голосов
/ 26 апреля 2018

Я создал класс связанного списка в Python и при вызове функции size, в которой я определил, я получаю следующую ошибку:

TypeError: get_next() missing 1 required positional argument: 'self'

Я попытался вызвать другую функцию, в которой я определил, которая также использует функцию get_next(), и она не выдает ошибку. Ниже приведено определение класса, а также тестовый код.

LinkedLists.py

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

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

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

    def insert(self, data):
        new_node = Node(data)

        new_node.set_next(self.head)
        self.head = new_node

    def size(self):
        current = self.head
        count = 0

        while current:
            count += 1
            current = current.get_next()

        return count

    def search(self, data):
        current = self.head
        found = False

        while current:
            if current.get_data() == data:
                found = True
            else:
                current = current.get_next()

        if current is None:
            raise ValueError("Data not in list")

        return current

    def delete(self, data):
        current = self.head
        previous = None
        found = False

        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                previous = current
                current = current.get_next()

        if current is None:
            raise ValueError("Data not in list")

        if previous is None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

    def insert_at(self, data, location):
        new_node = Node(data)
        current = self.head
        found = False

        while current and found is False:
            if current.get_data() == data:
                found = True
            else:
                current = current.get_next()

            if current is None:
                raise ValueError("Data not in list")

            new_node.set_next(current.get_next())

            current.set_next(new_node)

LinkedListsTest.py:

from LinkedLists import *

List = LinkedList()

List.insert(5)
List.insert(6)
List.insert(8)
List.delete(6)

print(List.size())

Полный возврат ошибки:

Traceback (most recent call last):
  File "LinkedListsTest.py", line 10, in <module>
    print(List.size())
  File ".../LinkedLists.py", line 31, in size
    current = current.get_next()
TypeError: get_next() missing 1 required positional argument: 'self'

Ответы [ 2 ]

0 голосов
/ 26 апреля 2018

Вы устанавливаете self.head для Node класса , а не экземпляра:

def __init__(self, head = Node):
    self.head = head

Обратите внимание на ссылку Node.Node.get_next() вызывает несвязанный метод, и self не передается.

Однако не устанавливайте head=Node() по умолчанию;значения по умолчанию устанавливаются один раз, во время определения функции, и изменяемое значение по умолчанию вызовет проблемы, поскольку все экземпляры вашего класса LinkedList будут совместно использовать этот один экземпляр.См. «Наименьшее изумление» и изменяемый аргумент по умолчанию .

. Вместо этого используйте часовую, например None, чтобы определить, что вам нужно создать значение по умолчанию:

def __init__(self, head=None):
    if head is None:
        # create an empty default
        head = Node()
    self.head = head

Сэто исправление, ваш тест печатает 3.

0 голосов
/ 26 апреля 2018

Предполагая, что я правильно интерпретировал правильный отступ, я думаю, что у вас может быть неправильный параметр по умолчанию:

class LinkedList(object):
    def __init__(self, head = Node()): # <== default should be instance
        self.head = head

Однако это может привести к неожиданным результатам.Вы могли иметь в виду это:

class LinkedList(object):
    def __init__(self, head = None):
        if head is None:
            head = Node()
        self.head = head
...