If someone writes a class in python, and fails to specify their own __repr__()
method, then a default one is provided for them. However, suppose we want to write a function which has the same, or similar, behavior to the default __repr__()
. However, we want this function to have the behavior of the default __repr__()
method even if the actual __repr__()
for the class was overloaded. That is, suppose we want to write a function which has the same behavior as a default __repr__()
regardless of whether someone overloaded the __repr__()
method or not. How might we do it?
class DemoClass:
def __init__(self):
self.var = 4
def __repr__(self):
return str(self.var)
def true_repr(x):
# [magic happens here]
s = "I'm not implemented yet"
return s
obj = DemoClass()
print(obj.__repr__())
print(true_repr(obj))
print(obj.__repr__())
prints 4
, but print(true_repr(obj))
prints something like:<__main__.DemoClass object at 0x0000000009F26588>
Introduction to the Python __repr__ magic method The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object. In other words, if you pass the returned string of the object_name.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.
__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.
You can use object.__repr__(obj)
. This works because the default repr
behavior is defined in object.__repr__
.
Note, the best answer is probably just to use object.__repr__
directly, as the others have pointed out. But one could implement that same functionality roughly as:
>>> def true_repr(x):
... type_ = type(x)
... module = type_.__module__
... qualname = type_.__qualname__
... return f"<{module}.{qualname} object at {hex(id(x))}>"
...
So....
>>> A()
hahahahaha
>>> true_repr(A())
'<__main__.A object at 0x106549208>'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With