如何通过名称获取Python Tree类的实例对象?
解决Tree类实例复用问题
首先你代码里有个基础错误:构造函数应该是__init__(前后双下划线),你写成了init,这会导致初始化逻辑根本不执行,不过先聚焦核心需求——通过名称获取已创建的实例。
问题根源是每次调用Tree("B")都会创建全新实例,而不是返回之前带B_cell的那个节点。要实现按名称复用实例,我们可以给Tree类加一个类级别的缓存字典存储已创建实例,再重写__new__方法(Python创建实例的入口方法),每次创建前先检查缓存,有同名实例就直接返回,没有再新建。
修改后的完整代码:
class Tree: # 类变量,存储所有已创建实例:键为name,值为实例对象 _instances = {} def __new__(cls, name, cell=""): # 优先从缓存取实例 if name in cls._instances: return cls._instances[name] # 缓存无对应实例时,创建新实例并存入缓存 instance = super().__new__(cls) cls._instances[name] = instance return instance def __init__(self, name, cell=""): # 标记是否已初始化,避免重复调用__init__覆盖数据 if hasattr(self, '_initialized'): return self.name = name self.cell = cell self.children = [] self.parent = None self._initialized = True def add_child(self, child): child.parent = self self.children.append(child)
测试你的代码:
node = Tree("A", cell = "A_cell") node.add_child(Tree("B", cell = "B_cell")) node.add_child(Tree("C", cell = "C_cell")) node.add_child(Tree("D", cell = "D_cell")) print(Tree("B").cell) # 输出:B_cell
关键说明:
_instances是类变量,所有Tree实例共享,用来记录每个名称对应的实例。__new__控制实例创建逻辑,先查缓存再决定是否新建,保证同名实例唯一。__init__里的_initialized标记是因为:即使返回已存在的实例,Python仍会调用__init__,用标记避免重复初始化覆盖原有数据。- 修正了原代码构造函数的拼写错误,这是功能正常运行的基础前提。
如果后续需要清空缓存,可添加类方法:
@classmethod def clear_instances(cls): cls._instances.clear()
内容的提问来源于stack exchange,提问作者Kanika Taneja
相关产品推荐
相关产品推荐

