【问题标题】:Python class attribute can't use its own objectPython类属性不能使用自己的对象
【发布时间】:2020-06-20 03:45:21
【问题描述】:

我是 python 新手,编写了两个类来定义一个单链表对象。我的 _Node 类有问题。对于 _Node 类的 'next' 属性,我想将其类型设置为 _Node 对象或 None,这就是我编写 Optional[_Node] 的地方。但是 Pycharm IDE 无法识别它。有人可以帮我解决这个问题吗?非常感谢。

from typing import Any, Optional

class _Node:
    """ A node in a linked list.

    Note that this is considered a "private class", one which is only meant
    to be used in this module by the LinkedList class, but not by client 
    code.

    === Attributes ===
    item:
        The data stored in this node.
    next:
        The next node in the List, or None if there are no more nodes.
    """

    item: Any
    next: Optional[_Node]

    def __init__(self, item: Any):
        """ Initialize a new node storing <item>, with no next node.
        """
        self.item = item
        self.next = None # Initailly pointing to nothing

【问题讨论】:

  • 请将代码和数据添加为文本 (using code formatting),而不是图像。图片:A)不允许我们复制粘贴代码/错误/数据进行测试; B) 不允许根据代码/错误/数据内容进行搜索;和many more reasons。一般来说,文本格式的代码/错误/数据>>>>作为图像的代码/错误/数据>>没有。除了代码格式的文本之外,只有在图像添加了一些重要的东西,而不仅仅是文本代码/错误/数据传达的内容时,才应该使用图像。
  • 感谢您的建议,因为这是我第一次在 Stact Overflow 上发布问题。我已根据您的评论更正了格式:)

标签: python class attributes nodes singly-linked-list


【解决方案1】:

您需要在文件顶部进行以下导入,以启用对具有 not yet been defined 的类的引用

from __future__ import annotations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多