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

Python自定义类方法中打印self输出实例内存地址问题求解

Python类实例打印可读信息修复方案

问题原因

  • 当你在f字符串中直接引用类实例self时,Python会自动调用实例的__str__方法获取字符串表示
  • 你自定义的Customer类没有重写__str__方法,默认继承自object基类的__str__方法,返回值就是内存地址格式的字符串,所以出现了你看到的输出

修复步骤

在Customer类内部添加自定义的__str__方法,指定实例转换为字符串时的输出规则即可,修改后的完整代码如下:

class Customer:
    """The people who are going to be accessing this program"""
    
    def __init__(self, first, last, gender, age):
        self.first = first 
        self.last = last
        self.gender = gender
        self.age = age
    
    # 新增自定义__str__方法
    def __str__(self):
        # 你可以根据需求调整输出格式,这里输出用户全名
        return f"{self.first} {self.last}"
    
    def buying_something(self):
        """The customer is now buying something"""
        print(f"{self} is now buying something")
    def browsing(self):
        """The customer is now browsing something"""
        print(f"{self} is now browsing something")

customer_1 = Customer('John', 'Doe', 'Male', 20)
print(f"This customers name is {customer_1.first}")
print(f"This customers age is {customer_1.age}")
customer_1.buying_something()

修复后输出结果

This customers name is John
This customers age is 20
John Doe is now buying something

拓展说明

如果需要在调试场景下也能看到相同的可读表示,可以在类中额外添加一行__repr__ = __str__,让实例的正式表示和非正式字符串表示保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:24:08