0

I have defined a class foo and a function foo.__str__(). If x is an instance of foo, x.__str__() returns a string representation of x. I have checked this on examples and it seems to work as I wish it to.

My question is, how to I now define foo.print(). Am I supposed to use __str__ or, annoyingly, repeat the code of __str__?

Jon Clements
  • 132,101
  • 31
  • 237
  • 267
David Epstein
  • 373
  • 3
  • 13

1 Answers1

3

No, print just calls __str__, so you dont need to do anything else. You probably will also need to define __repr__, which returns the representation of the object

Code

class A:
    def __str__(self):
        return 'in __str__'

    def __repr__(self):
        return 'in __repr__'

a = A()

print(a) # __str__
print([a]) # __repr__

Output

enter image description here

Look at this post about __str__ vs __repr__

JoshuaCS
  • 2,368
  • 1
  • 12
  • 16