1

I have a list A of instances of a certain class. I want to change what returns when I do print(A).

A = [MyClass(i) for i in range(10)]
print(A)
[<__main__.MyClass at 0x7f286808a2b0>,
 <__main__.MyClass at 0x7f286808a320>,
 <__main__.MyClass at 0x7f286808a780>,
 <__main__.MyClass at 0x7f286808a7f0>,
 <__main__.MyClass at 0x7f286808a860>,
 <__main__.MyClass at 0x7f286808a710>,
 <__main__.MyClass at 0x7f286808a940>,
 <__main__.MyClass at 0x7f286808a8d0>,
 <__main__.MyClass at 0x7f286808ada0>,
 <__main__.MyClass at 0x7f286808ad30>]  

I would rather maybe had as return something like

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

How can I do this?

  • You need to implement `__repr__` function under your MyClass – Chen A. Apr 08 '18 at 14:33
  • 2
    Possible duplicate of [How to print a class or objects of class using print()?](https://stackoverflow.com/questions/1535327/how-to-print-a-class-or-objects-of-class-using-print) – Aran-Fey Apr 08 '18 at 14:37

3 Answers3

1

What you want is to change the default representation of an object. This is done by implementing the __repr__ function.

class MyClass(object):
    def __init__(self, i):
        self.i = i

    def __repr__(self):
        return str(self.i)


>>> A = [MyClass(i) for i in range(3)]
>>> print A
[0, 1, 2]

When you call print on an object, the object executes __str__. Since A is a list (container), the container executes each object __repr__ function instead.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
1

You need to define a __repr__ method inside MyClass, obtaining something like this:

class MyClass():
    def __init__(self, i):
        self.i = i
    def __repr__(self):
        return str(self.i)

print([MyClass(i) for i in range(3)]) # prints '[0, 1, 2]'
Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31
  • 1
    That's wrong. Implementing `__str__` still won't change the output, since when you call print on a container it prints the objects `__repr__` – Chen A. Apr 08 '18 at 14:38
  • 1
    Yes, and your code works because you print `MyClass` object. If you put it inside a container like the OP question, you will see it won't work. Try this: `a = [MyClass(3)]; print a` – Chen A. Apr 08 '18 at 14:43
1

If this is for an isolated task, you can retrieve the argument as part of a list comprehension:

class MyClass(object):
    def __init__(self, var):
        self.var = var

A = [MyClass(i) for i in range(10)]

print([x.var for x in A])

# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Otherwise, as demonstrated by @Vinny, you can add a __repr__ method to your class.

jpp
  • 159,742
  • 34
  • 281
  • 339