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

如何在Python中获取__repr__()的默认行为(不受重载影响)

How to Get the Default __repr__() Behavior Ignoring Class Overrides

Got it, let's break this down. When you don't define a custom __repr__() for a Python class, the default implementation from the object base class returns a string formatted like <Module.ClassName object at 0xMemoryAddress>. If your class has overridden __repr__(), calling obj.__repr__() will use that custom version—but you want a way to bypass that and get the original default output.

The Solution: Directly Call object's __repr__ Method

The trick is to skip the subclass's overridden method and invoke the base object class's __repr__ directly. Here's a simple function that does exactly that:

def get_default_repr(obj):
    return object.__repr__(obj)

How It Works

Every Python class inherits from object (even if you don't specify it explicitly). When you call object.__repr__(obj), you're bypassing any custom __repr__() implementation in the object's class and using the original default logic. This ensures you always get that classic <Class object at ...> format, no matter what the class has defined.

Example Usage

Let's test this with a class that has a custom __repr__():

class TestClass:
    def __repr__(self):
        return "I'm a custom repr!"

# Create an instance
test_obj = TestClass()

# Get default repr (ignores custom implementation)
print(get_default_repr(test_obj))  # Output: <__main__.TestClass object at 0x...>

# Compare with the custom repr
print(test_obj.__repr__())  # Output: I'm a custom repr!

Edge Cases to Note

  • This works for all Python objects, including built-in types (though most built-ins have their own custom __repr__(), but if you ever need the base object version, this function will get it).
  • It doesn't modify the object or its class in any way—it just returns the default representation string.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:58:19