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
  • 138,671
  • 33
  • 247
  • 280
David Epstein
  • 433
  • 4
  • 14

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,524
  • 1
  • 13
  • 16