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

为何__repr__方法未显式调用却能输出Item类列表内容?

问题解答

先看你提供的代码:

class Item:
    pay_rate = 0.8 # The pay rate after 20% discount
    all = []
    def __init__(self, name: str, price: float, quantity=0):
        # Run validations to the received arguments
        assert price >= 0, f"Price {price} is not greater than or equal to zero!"
        assert quantity >= 0, f"Quantity {quantity} is not greater or equal to zero!"

        # Assign to self object
        self.name = name
        self.price = price
        self.quantity = quantity

        # Actions to execute
        Item.all.append(self)

    def calculate_total_price(self):
        return self.price * self.quantity

    def apply_discount(self):
        self.price = self.price * self.pay_rate

    def __repr__(self):
        return f"Item('{self.name}', {self.price}, {self.quantity})"

item1 = Item("Phone", 100, 1)
item2 = Item("Laptop", 1000, 3)
item3 = Item("Cable", 10, 5)
item4 = Item("Mouse", 50, 5)
item5 = Item("Keyboard", 75, 5)

print(Item.all)

针对你的疑问,解释如下:

  • 为什么__repr__不需要直接调用?
    __repr__是Python的特殊魔术方法,这类方法的设计逻辑就是由Python解释器自动触发,而非手动调用。它的核心作用是返回对象的“官方可解析”字符串表示,当Python需要将对象转换为字符串时(比如打印对象、在交互式控制台显示对象),会自动调用该方法。比如你直接写print(item1),Python内部会自动执行item1.__repr__(),这个过程不需要你显式写代码触发。

  • 为什么打印Item.all会触发__repr__?
    Item.all是一个存储Item实例的列表。当你打印列表时,Python会遍历列表中的每一个元素,对每个元素自动调用其__repr__方法,把返回的字符串拼接成列表的标准打印格式(方括号包裹、元素间用逗号分隔)。如果没有自定义__repr__,Python会用默认实现,打印出类似<__main__.Item object at 0x00000123456789AB>的内存地址信息,完全不利于查看对象的实际内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:32:39