Overload __str__ method for user-friendly message

Overload __str__


class MyClass(object):
    def __init__(self, name):
        self.name = name#   w w w .j  a va  2 s  . co  m

    def __str__(self):
        rep = "MyClass object\n"
        rep += "name: " + self.name + "\n"
        return rep

    def __cmp__(self, other):
        if self.name > other.name:
            return 1
        if self.name < other.name:
            return -1
        if self.name == other.name:
            return 0      

    def talk(self):
        print "Hi.  I'm", self.name, "\n"

crit1 = MyClass("A")
crit1.talk()

crit2 = MyClass("B")
crit2.talk()

print crit1

print crit1.name

The code above generates the following result.

__str__ is tried first for user-friendly displays.


class Time60(object):            
    def __init__(self, hr, min): 
        self.hr = hr             # w  ww . ja va  2 s  . com
        self.min = min           
    def __str__(self):
        return '%d:%d' % (self.hr, self.min)

mon = Time60(10, 30)
tue = Time60(11, 15)

print mon, tue

The code above generates the following result.

The following code uses __str__ to output message for an Employee class.


class Employee:#   w  ww  .  j a  va2 s  . c  o m
   def __init__( self, first, last ):
      self.firstName = first
      self.lastName = last

   def __str__( self ):
      return "%s %s" % ( self.firstName, self.lastName )

class HourlyWorker( Employee ):
   def __init__( self, first, last, initHours, initWage ):
      Employee.__init__( self, first, last )
      self.hours = float( initHours )
      self.wage = float( initWage )

   def getPay( self ):
      return self.hours * self.wage

   def __str__( self ):
      print "HourlyWorker.__str__ is executing"""      
      return "%s is an hourly worker with pay of $%.2f" % ( Employee.__str__( self ), self.getPay() )

hourly = HourlyWorker( "Bob", "Smith", 40.0, 10.00 )
print hourly 
print hourly.__str__()  
print HourlyWorker.__str__( hourly )  

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules