【问题标题】:Can you overwrite / substitute "self" for another variable in the method?你能用“self”覆盖/替换方法中的另一个变量吗?
【发布时间】:2022-06-15 22:42:02
【问题描述】:

我正在尝试构建一个可用于递归查找父链接的函数,但为此,我需要在第一次迭代后使用父变量调用 get_ancestors() 函数,而不是自变量。这是否违反了某种规则?

    def get_ancestors(self, ancestors):
        parents = []
        for uid in self.links:
            parents.append(self.tree.find_item(uid))
        for parent in parents:
            if parent.links:
                self.get_ancestors(parent, ancestors)
            else:
                if parent not in ancestors:
                    ancestors.append(parent)
        return ancestors

【问题讨论】:

  • self 通常是调用该方法的对象 - 你能调用parent.get_ancestors(ancestors)吗?
  • 您将使用parent.get_ancestors(X) 进行递归调用。

标签: python


猜你喜欢
  • 1970-01-01
  • 2011-01-28
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
  • 2020-09-20
相关资源
最近更新 更多