By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,089 Members | 2,418 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,089 IT Pros & Developers. It's quick & easy.

Is there a way to define a default print for a class?

P: 4
I have a class and I am printing an instance of it:

Expand|Select|Wrap|Line Numbers
  1. class Complex:
  2.   def __init__( self, realpart, imagpart = 0 ):
  3.     self.r = realpart
  4.     self.i = imagpart
  5.  
  6.   def show( self ):
  7.     print "(" + str( self.r ) + ", " + str( self.i ) + ")"
  8.  
  9. x = Complex( 1, 2 )
  10. x.show()
  11. print x

This is what gets printed out:
Expand|Select|Wrap|Line Numbers
  1. (1, 2)
  2. <__main__.Complex instance at 0x0150C030>
  3.  
Is there a way that we can define a default way to print our class to make the "print x" line print the same way as the "x.show()"?
Aug 10 '07 #1
Share this Question
Share on Google+
3 Replies


ilikepython
Expert 100+
P: 844
I have a class and I am printing an instance of it:

Expand|Select|Wrap|Line Numbers
  1. class Complex:
  2.   def __init__( self, realpart, imagpart = 0 ):
  3.     self.r = realpart
  4.     self.i = imagpart
  5.  
  6.   def show( self ):
  7.     print "(" + str( self.r ) + ", " + str( self.i ) + ")"
  8.  
  9. x = Complex( 1, 2 )
  10. x.show()
  11. print x

This is what gets printed out:
Expand|Select|Wrap|Line Numbers
  1. (1, 2)
  2. <__main__.Complex instance at 0x0150C030>
  3.  
Is there a way that we can define a default way to print our class to make the "print x" line print the same way as the "x.show()"?
Yea, you use the __str__ or __repr__:
Expand|Select|Wrap|Line Numbers
  1. class whatever:
  2.     def __str__(self):
  3.         return "Test"
  4.  
  5. x = whatever()
  6. print x
  7.  
Aug 11 '07 #2

P: 4
Wow thanks that works perfectly! I swear I checked google first...
Aug 11 '07 #3

bartonc
Expert 5K+
P: 6,596
Wow thanks that works perfectly! I swear I checked google first...
That's probably how you ended up finding the best Python forum on the web...
Aug 11 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.