You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类方法返回对象内存地址而非数据值的问题求助

解决自定义类返回内存地址而非数据值的问题

Python中,当你打印自定义类的实例时,默认会输出对象的内存地址,这是因为没有为类定义__str__或__repr__方法来指定对象的字符串表示形式。针对你的问题,提供两种解决方案:

方案1:为Node类添加字符串表示方法

在Node类中定义__str__(或__repr__)方法,这样打印Node对象时会自动返回你期望的数据值:

class Node: 
    def __init__(self, data):
        self.data = data 
    
    def __str__(self):
        # 返回data的字符串形式,可按需自定义格式
        return str(self.data)

class BinaryTree:
    root = None  
    @classmethod
    def InsertNode(cls, data):
        newNode = Node(data)
        if cls.root == None:
            cls.root = newNode
            return cls.root
        else: 
            queue = []
            queue.append(cls.root)
        # 注意:你的else分支目前未完成后续插入逻辑,需补充完整

print(BinaryTree().InsertNode(4))  # 现在会输出4

如果需要在交互式调试环境中也能看到清晰的对象信息,可以同时定义__repr__方法:

def __repr__(self):
    return f"Node(data={self.data})"

方案2:修改InsertNode方法直接返回数据值

如果业务逻辑不需要返回Node对象本身,可直接修改方法的返回值:

class Node: 
    def __init__(self, data):
        self.data = data 

class BinaryTree:
    root = None  
    @classmethod
    def InsertNode(cls, data):
        newNode = Node(data)
        if cls.root == None:
            cls.root = newNode
            return newNode.data  # 这里返回data而非Node对象
        else: 
            queue = []
            queue.append(cls.root)
        # 补充完else分支的插入逻辑后,记得返回对应的数据或对象

print(BinaryTree().InsertNode(4))  # 输出4

注意:你的BinaryTree.InsertNode方法的else分支目前缺少完整的节点插入逻辑,仅实现了根节点的插入,需要补充后续的遍历和插入代码才能支持非根节点的添加。

内容的提问来源于stack exchange,提问作者ARIANA MONDIRI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:36:29