Python 3 объявляет экземпляр внутри функции с ошибкой требуемого позиционного аргумента: ошибка ‘self’

#python #python-3.x #python-2.7

#python #python-3.x #python-2.7

Вопрос:

Я новичок в Python и пытаюсь преобразовать старый класс FPNode из python 2 в 3, это полный код:

 class FPNode(object):
    """A node in an FP tree."""

    def __init__(self, tree, item, count=1):
        self._tree = tree
        self._item = item
        self._count = count
        self._parent = None
        self._children = {}
        self._neighbor = None
        self.transactions = {}

    def add(self, child):
        """Adds the given FPNode `child` as a child of this node."""

        if not isinstance(child, FPNode):
            raise TypeError("Can only add other FPNodes as children")

        if not child.item in self._children:
            self._children[child.item] = child
            child.parent = self

    def search(self, item):
        """
        Checks to see if this node contains a child node for the given item.
        If so, that node is returned; otherwise, `None` is returned.
        """

        try:
            return self._children[item]
        except KeyError:
            return None

    def remove(self, child):
        try:
            if self._children[child.item] is child:
                del self._children[child.item]
                child.parent = None
                self._tree._removed(child)
                for sub_child in child.children:
                    try:
                        # Merger case: we already have a child for that item, so
                        # add the sub-child's count to our child's count.
                        self._children[sub_child.item]._count  = sub_child.count
                        sub_child.parent = None  # it's an orphan now
                    except KeyError:
                        # Turns out we don't actually have a child, so just add
                        # the sub-child as our own child.
                        self.add(sub_child)
                child._children = {}
            else:
                raise ValueError("that node is not a child of this node")
        except KeyError:
            raise ValueError("that node is not a child of this node")

    def __contains__(self, item):
        return item in self._children

    @property
    def tree(self):
        """The tree in which this node appears."""
        return self._tree

    @property
    def item(self):
        """The item contained in this node."""
        return self._item

    @property
    def count(self):
        """The count associated with this node's item."""
        return self._count

    def increment(self):
        """Increments the count associated with this node's item."""
        if self._count is None:
            raise ValueError("Root nodes have no associated count.")
        self._count  = 1

    @property
    def root(self):
        """True if this node is the root of a tree; false if otherwise."""
        return self._item is None and self._count is None

    @property
    def leaf(self):
        """True if this node is a leaf in the tree; false if otherwise."""
        return len(self._children) == 0

    def parent(self):
        doc = "The node's parent."

        def fget():
            return self._parent

        def fset(value):
            if value is not None and not isinstance(value, FPNode):
                raise TypeError("A node must have an FPNode as a parent.")
            if value and value.tree is not self.tree:
                raise ValueError("Cannot have a parent from another tree.")
            self._parent = value

        return locals()

    parent = property(**parent())

    def neighbor(self):
        doc = """
        The node's neighbor; the one with the same value that is "to the right"
        of it in the tree.
        """

        def fget(self):
            return self._neighbor

        def fset(self, value):
            if value is not None and not isinstance(value, FPNode):
                raise TypeError("A node must have an FPNode as a neighbor.")
            if value and value.tree is not self.tree:
                raise ValueError("Cannot have a neighbor from another tree.")
            self._neighbor = value

        return locals()

    neighbor = property(**neighbor())

    @property
    def children(self):
        """The nodes that are children of this node."""
        return tuple(self._children.itervalues())

    def inspect(self, depth=0):
        print('  ' * depth)   repr(self)
        for child in self.children:
            child.inspect(depth   1)

    def __repr__(self):
        if self.root:
            return "<%s (root)>" % type(self).__name__
        return "<%s %r (%r) %r>" % (type(self).__name__, self.item, self.count, self.transactions)
 

когда я пытаюсь запустить свой код, я получаю следующую ошибку:

     parent = property(**parent())
TypeError: parent() missing 1 required positional argument: 'self'
 

исходный класс в python 2 не содержится "self" в def parent(): функции, но python 3 этого не допускает.
та же проблема возникает и с the neighbor = property(**neighbor()) , и я понятия не имею, как это исправить, любая помощь будет высоко оценена

Комментарии:

1. Это никогда бы не сработало в Python 2, даже с def parent(): тем, что, как вы говорите, было в исходной версии. Любая попытка фактического доступа к parent свойству завершится неудачей. (Я подозреваю, что это связано с дополнительными ошибками, которые вы ввели, не осознавая этого — реальная исходная версия parent , вероятно, работала бы без изменений.)

2. neighbor могло бы сработать, self если бы вы не добавили def neighbor(self): . Почему вы добавили self к параметрам parent and neighbor ?

3. @user2357112supportsMonica вы правы, я удалил self из обеих функций, и теперь он работает. Я добавил его в первую очередь потому, что PyCharm выдал его как ошибку, когда я переключился на интерпретатор Python 3.8