pythonoutputpythoninterpreter

What determines output when executing single variable in python interpreter?


So take the complex built-in type as an example. I am making my own version of Complex for educational purposes, however as of now, they aren't behaving the same way. When I run

>>> a = (2+3j)
>>> a
(2+3j)
>>> from complex import Complex # My version of the type
>>> b = Complex(2, 3)
>>> b
<complex.Complex object at 0x10caeb0f0>

I want my class to output the same thing. I always thought that this was the purpose of the str magic method, but that only gets invoked when something is trying to convert the instance to string, which isn't happening in the example above. How to do this?


Solution

  • Use __repr__:

    class Complex:
      def __init__(self, i, j):
        self.i = i
        self.j = j
    
      def __repr__(self):
        return f'({self.i}, {self.j}j)'
    
    b = Complex(2, 3)
    print(b)
    

    Output:

    (2, 3j)