Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we get the default behavior of __repr__()?

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))

Desired Output:

print(obj.__repr__()) prints 4, but print(true_repr(obj)) prints something like:
<__main__.DemoClass object at 0x0000000009F26588>

like image 867
Toothpick Anemone Avatar asked Feb 13 '18 22:02

Toothpick Anemone


People also ask

How is the __ repr __ magic method used?

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.

How do you call the __ str __ method?

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.

What does def __ repr __( self do?

According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__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.


2 Answers

You can use object.__repr__(obj). This works because the default repr behavior is defined in object.__repr__.

like image 50
internet_user Avatar answered Oct 25 '22 22:10

internet_user


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>'
>>>
like image 39
juanpa.arrivillaga Avatar answered Oct 25 '22 22:10

juanpa.arrivillaga