如何在不传递调用对象的情况下将函数从一个类移动到另一个类

2024-10-03 04:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据结构(Trie)的实现,它按预期工作。我有一个主类Node和一个包装类Trie。我想将函数_insert()Node类移到Trie类,以使Node尽可能简单。但是我面临着很多问题,比如class Trie has no object nodes and no object word.有没有一种方法可以在不将调用对象从main传入的情况下完成呢? 期望值:

trie.insert("Hi")

类Trie中insert()的所有实现

class Node:
    def __init__(self):
        self.word = None
        self.nodes = {}

    def _insert(self, word, string_pos=0):
        current_lettter = word[string_pos]
        if current_lettter not in self.nodes:
            self.nodes[current_lettter] = Node()
        if(string_pos + 1 == len(word)):
            self.nodes[current_lettter].word = word
        else:
            self.nodes[current_lettter]._insert(word, string_pos + 1)

        return True


class Trie:

    def __init__(self):
        self.root = Node()

    def insert(self, word):
        self.root._insert(word)

trie = Trie()
trie.insert("Hi") 

Tags: noposselfnodestringobjectdefcurrent