Search code examples
pythonfor-looprepr

How do I get .__repr__() to work correctly?


I want to use __repr__ in Python, so I can see the representation the way I want it to be like below.

class Polynomial:
    def __init__(self, *args):
        self.args = args
        def __repr__(self):
            Repr = "Polynomial("
            for i in args:
                if i == 0:
                    Repr = Repr + str(self.args[i])
                else:
                    Repr = Repr + ", "+ str(self.args[i])
            return Repr

so if I enter Polynomial(1,2,3), it should return 'Polynomial(1,2,3)', not like <__main__.Polynomial at 0x219eb9f52c8>. But it still returns that uninformative stuff. Where did I do wrong?


Solution

  • You have multiple issues:

    1. Your indentation is incorrect, __repr__ should be a method of your class. It is currently an inner method of your __init__ method.
    2. You are iterating args but you are trying to use i as if it is the index (it is the actual arg)
    3. You can use .join() to easily convert a list to a comma separated string.

    Here is a working implementation of your method:

    class Polynomial:
        def __init__(self, *args):
            self.args = args
        def __repr__(self):
            Repr = "Polynomial("
            for i in range(len(self.args)):
                if i == 0:
                    Repr = Repr + str(self.args[i])
                else:
                    Repr = Repr + ", "+ str(self.args[i])
            Repr += ")"
            return Repr
    

    And this is a more streamlined method that uses string formatting and .join()::

    class Polynomial:
        def __init__(self, *args):
            self.args = args
        def __repr__(self):
            return "Polynomial({})".format(", ".join([str(arg) for arg in self.args]))