【问题标题】:How to use a class within itself [duplicate]如何在自身内部使用一个类[重复]
【发布时间】:2020-12-09 20:06:44
【问题描述】:

我对 Python 非常非常陌生(来自 Java 和 C++),所以这可能是非常基础的,有点尴尬:

我正在尝试在该类中使用一个类的实例,但我的 IDE (PyCharm) 告诉我它是一个未解析的引用 例如(这只是一个例子,所以请不要“只使用一些已经存在的 Node 类”)

class Node(object):
    def addChild(self, node: Node): # the word Node here is where the error happens
        self.children.append(node)

我尝试在谷歌上搜索各种短语,并且在过去的几个小时里阅读了几个教程,但我只是不明白我在这里做错了什么,或者我如何在定义类之前声明它。还是 IDE 建议的那样,在上面添加一个额外的“class Node(object): pass”真的是这样做的吗?

【问题讨论】:

标签: python


【解决方案1】:

这样试试:

class Node:
  def __init__(self):       
    self.children = []
  def addChild(self, node): # the word Node here is where the error happens
    self.children.append(node)
  def showNode(self):
    print(self.children)


nd = Node()
nd.addChild("oi")
nd.addChild("Tchau")
nd.showNode()

【讨论】:

  • 这根本不涉及类型提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多