如何在Python中获取__repr__()的默认行为(不受重载影响)
__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 baseobjectversion, 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

