Chapter 8: Operator Overloading

Example 8.1, Page Number 321

In [1]:
class Counter:                              
    def __init__(self):                   #constructor
        self.__count = 0
        
    def get_count(self):                  #return count
        return self.__count
    
    def __iadd__(self,other):             #increment
        self.__count += other
        return self
        
        
        
c1 = Counter()                            #define and initialize
c2 = Counter()

print 'c1 =',c1.get_count()               #display
print 'c2 =',c2.get_count()

c1 += 1                                   #increment c1
c2 += 1                                   #increment c2
c2 += 1                                   #increment c3

print 'c1 =',c1.get_count()               #display again
print 'c2 =',c2.get_count()
c1 = 0
c2 = 0
c1 = 1
c2 = 2

Example 8.2, Page Number 324

In [2]:
class Counter:
    def __init__(self):                   #constructor
        self.count = 0
        
    def get_count(self):                  #return count
        return self.count
    
    def __iadd__(self,other):             #increment count
        
        self.count += other               #increment count
        temp = Counter()                  #make a temporary Counter
        temp.count = self.count           #give it same value as this obj
        return temp                       #return the copy
        
        
        
c1 = Counter()                            #c1=0, c2=0
c2 = Counter()

print 'c1 =',c1.get_count()               #display
print 'c2 =',c2.get_count()

c1 += 1                                   #c1=1
c1 += 1                                   #c1=2, c2=2
c2 = c1
 
print 'c1 =',c1.get_count()               #display again
print 'c2 =',c2.get_count()
c1 = 0
c2 = 0
c1 = 2
c2 = 2

Example 8.3, Page Number 325

In [3]:
class Counter:
    def __init__(self,c=0):                #overloaded constructor
        self.__count = c
        
    def get_count(self):                   #return count
        return self.__count
    
    def __iadd__(self,other):              #increment count
        
        self.__count += other              #increment count, then return 
        return Counter(self.__count)       #an unnamed temporary object initialized to this count
        
        
        
c1 = Counter()                            #c1=0, c2=0
c2 = Counter()

print 'c1 =',c1.get_count()               #display
print 'c2 =',c2.get_count()

c1 += 1                                   #c1=1
c1 += 1                                   #c1=2, c2=2
c2 = c1
 
print 'c1 =',c1.get_count()               #display again
print 'c2 =',c2.get_count()
c1 = 0
c2 = 0
c1 = 2
c2 = 2

Example 8.4, Page Number 327

In [4]:
from copy import deepcopy

class Counter:
    def __init__(self,c=0):                     #constructor 
        self.__count = c
        
    def get_count(self):                        #return count
        return self.__count
    
    def __iadd__(self,other):                  #increment count (prefix & postifix both)  ; 'In python no ++ opertor is there'
        self.__count += other
        return Counter(self.__count)
        
        
        
c1 = Counter()                                 #c1=0, c2=0
c2 = Counter()

print 'c1 =',c1.get_count()                    #display
print 'c2 =',c2.get_count()

c1 += 1                                        #c1=1
c1 += 1                                        #c1=2, c2=2
c2 = c1

print 'c1 =',c1.get_count()                    #display
print 'c2 =',c2.get_count() 

c2 = deepcopy(c1)
c1 += 1                                        #c1=3, c2=3

print 'c1 =',c1.get_count()                    #display again
print 'c2 =',c2.get_count()
c1 = 0
c2 = 0
c1 = 2
c2 = 2
c1 = 3
c2 = 2

Example 8.5, Page Number 329

In [5]:
class Distance:                                              #class Distance
    def __init__(self,ft=0,inc=0.0):                         #overloaded constructor
        self.__feet = ft
        self.__inches = inc
        
    def getdist(self):                                       #get length from user
        self.__feet = input("Enter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):                                     #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
    def __add__(self,d2):                                   #add 2 distances
        f = self.__feet + d2.__feet                         #add the feet
        i = self.__inches + d2.__inches                     #add the inches
         
        if i >= 12.0:                   #if total exceeds 12.0
            i -= 12.0                   #decrease inches by 12.0 and
            f += 1                      #increase feet by 1
            
        return Distance(f,i)            #return a temporary Distance initialized to sum

    
    
dist1 = Distance()                      #define distances
dist3 = Distance()
dist4 = Distance()
dist1.getdist()                         #get dist1 from user

dist2 = Distance(11,6.25)               #define , initialize dist2

dist3 = dist1 + dist2                   #single '+' operator

dist4 = dist1 + dist2 + dist3           #multiple '+' operator

print '\ndist1 =',; dist1.showdist()    #display all length
print 'dist2 =',;   dist2.showdist()
print 'dist3 =',;   dist3.showdist()
print 'dist4 =',;   dist4.showdist()
Enter feet: 10
Enter inches: 6.5

dist1 = 10 ' - 6.5 "
dist2 = 11 ' - 6.25 "
dist3 = 22 ' - 0.75 "
dist4 = 44 ' - 1.5 "

Example 8.6, Page Number 332

In [6]:
class String:                                    #user - defined string type
    __SZ = 80                                    #size of String objects
    
    def __init__(self,s=""):                     #overloaded constructor
        self.__str = s
        
    def display(self):                           #display string
        print self.__str ,
        
    def __add__(self,ss):                        #add strings
        temp = String()                          #make temporary string
        
        if len(self.__str) + len(ss.__str) < self.__SZ:
            temp.__str = self.__str + " " + ss.__str              #add this string and arg string to temp string
            
        else:
            print '\nString overflow'
            raise SystemExit 
            
        return temp                              #return temp string
     
        
        
s1 = String("\nMerry Christmus!  ")              #intialize the string variables
s2 = String("Happy new year!")
s3 = String()

s1.display()                                     #display strings
s2.display()  
s3.display()

s3 = s1 + s2                                     #add s2 to s1 and assign to s3
s3.display()                                     #display s3
print
Merry Christmus!   Happy new year!  
Merry Christmus!   Happy new year!

Example 8.7, Page Number 334

In [7]:
class Distance:                                                  #class Distance
    def __init__(self,ft=0,inc=0.0):                             #overloaded constructor
        self.__feet = ft 
        self.__inches = inc
        
    def getdist(self):                                           #get length from user
        self.__feet = input("Enter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):                                          #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
    def __lt__(self,d2):                                         #compare this distance with d2
        bf1 = self.__feet + self.__inches/12
        bf2 = d2.__feet + d2.__inches/12
        
        return bf1 < bf2
    
    

dist1 = Distance()                          #define Distance dist1
dist1.getdist()                             #get dist1 from user

dist2 = Distance(11,6.25)                   #define and initialize dist2

print '\ndist1 =',; dist1.showdist()        #display Distances

print 'dist2 =',; dist2.showdist()

if dist1 < dist2:                           #overloaded '<' operator
    print 'dist1 is less than dist2'
else:
    print 'dist2 is greater than (or equal to) dist2'
Enter feet: 5
Enter inches: 11.5

dist1 = 5 ' - 11.5 "
dist2 = 11 ' - 6.25 "
dist1 is less than dist2

Example 8.8, Page Number 336

In [8]:
class String:                                       #user-define String type
    __SZ = 80                                       #size of string objects
    def __init__(self,s=""):                        #constructor
        self.__str = s
        
    def display(self):                              #display a string
        print self.__str ,
        
    def getstr(self):                               #read a string
        self.__str = raw_input()
        
    def __eq__(self,ss):                            #check for equality
        return self.__str == ss.__str
    
    
    
s1 = String("yes")
s2 = String("no")
s3 = String()

print "\n Enter 'yes' or 'no': ",
s3.getstr()                                        #get string from user

if s3 == s1:                                       #compare from "yes"
    print 'You typed yes\n'
elif s3 == s2:                                     #compare from "no"
    print 'you typed no\n'
else:
    print "you didn't follow instructions\n"
 Enter 'yes' or 'no': yes
 You typed yes

Example 8.9, Page Number 337

In [9]:
class Distance:                                              #class Distance
    def __init__(self,ft=0,inc=0.0):                         #constructor
        self.__feet = ft
        self.__inches = inc
        
    def getdist(self):                                       #get length from user
        self.__feet = input("Enter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):                                      #display Distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
    def __iadd__(self,d2):                                   #add distance to this one
        self.__feet = self.__feet + d2.__feet                #add the feet
        self.__inches = self.__inches + d2.__inches          #add the inches
        
        if self.__inches >= 12.0:                            #if total exceeds 12.0, 
            self.__inches -= 12.0                            #then decrease inches by 12.0 and
            self.__feet += 1                                 #increase feet by 1
            
        return self

    
    
dist1 = Distance()                       #define dist1
dist1.getdist()                          #get dist1 from user
print '\ndist1 =',; dist1.showdist()

dist2 = Distance(11,6.25)                #define, initialize dist2
print 'dist2 =',; dist2.showdist()

dist1 += dist2                           #dist1 = dist1 + dist2

print 'After addition,'

print 'dist1 =',; dist1.showdist()
Enter feet: 3
Enter inches: 5.75

dist1 = 3 ' - 5.75 "
dist2 = 11 ' - 6.25 "
After addition,
dist1 = 15 ' - 0.0 "

Example 8.10, Page Number 340

In [10]:
LIMIT = 100

class safearay:
    __arr = [0 for j in range(LIMIT)]
    
    def putel(self,n,elvalue):                #set value of element
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        self.__arr[n] = elvalue
        
    def getel(self,n):                        #get value of element 
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        return self.__arr[n]
    
    
    
sa1 = safearay()
 
for j in range(LIMIT):                        #insert element
    sa1.putel(j,j*10)
    
for j in range(LIMIT):                        #display element
    temp = sa1.getel(j)
    print 'Element',j,'is',temp
Element 0 is 0
Element 1 is 10
Element 2 is 20
Element 3 is 30
Element 4 is 40
Element 5 is 50
Element 6 is 60
Element 7 is 70
Element 8 is 80
Element 9 is 90
Element 10 is 100
Element 11 is 110
Element 12 is 120
Element 13 is 130
Element 14 is 140
Element 15 is 150
Element 16 is 160
Element 17 is 170
Element 18 is 180
Element 19 is 190
Element 20 is 200
Element 21 is 210
Element 22 is 220
Element 23 is 230
Element 24 is 240
Element 25 is 250
Element 26 is 260
Element 27 is 270
Element 28 is 280
Element 29 is 290
Element 30 is 300
Element 31 is 310
Element 32 is 320
Element 33 is 330
Element 34 is 340
Element 35 is 350
Element 36 is 360
Element 37 is 370
Element 38 is 380
Element 39 is 390
Element 40 is 400
Element 41 is 410
Element 42 is 420
Element 43 is 430
Element 44 is 440
Element 45 is 450
Element 46 is 460
Element 47 is 470
Element 48 is 480
Element 49 is 490
Element 50 is 500
Element 51 is 510
Element 52 is 520
Element 53 is 530
Element 54 is 540
Element 55 is 550
Element 56 is 560
Element 57 is 570
Element 58 is 580
Element 59 is 590
Element 60 is 600
Element 61 is 610
Element 62 is 620
Element 63 is 630
Element 64 is 640
Element 65 is 650
Element 66 is 660
Element 67 is 670
Element 68 is 680
Element 69 is 690
Element 70 is 700
Element 71 is 710
Element 72 is 720
Element 73 is 730
Element 74 is 740
Element 75 is 750
Element 76 is 760
Element 77 is 770
Element 78 is 780
Element 79 is 790
Element 80 is 800
Element 81 is 810
Element 82 is 820
Element 83 is 830
Element 84 is 840
Element 85 is 850
Element 86 is 860
Element 87 is 870
Element 88 is 880
Element 89 is 890
Element 90 is 900
Element 91 is 910
Element 92 is 920
Element 93 is 930
Element 94 is 940
Element 95 is 950
Element 96 is 960
Element 97 is 970
Element 98 is 980
Element 99 is 990

Example 8.11, Page Number 341

In [11]:
LIMIT = 100

class safearay:
    __arr = [0 for j in range(LIMIT)]
    
    def access1(self,n,n1):                  #function for set the value in the array 
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        self.__arr[n] = n1
        
    def access2(self,n):                     #function for return the array
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        return self.__arr[n]
    
    
    
sa1 = safearay()

for j in range(LIMIT):                       #insert elements using first function
    sa1.access1(j,j*10)
    
for j in range(LIMIT):                       #display elements using second function
    temp = sa1.access2(j)
    print 'Element',j,'is',temp
Element 0 is 0
Element 1 is 10
Element 2 is 20
Element 3 is 30
Element 4 is 40
Element 5 is 50
Element 6 is 60
Element 7 is 70
Element 8 is 80
Element 9 is 90
Element 10 is 100
Element 11 is 110
Element 12 is 120
Element 13 is 130
Element 14 is 140
Element 15 is 150
Element 16 is 160
Element 17 is 170
Element 18 is 180
Element 19 is 190
Element 20 is 200
Element 21 is 210
Element 22 is 220
Element 23 is 230
Element 24 is 240
Element 25 is 250
Element 26 is 260
Element 27 is 270
Element 28 is 280
Element 29 is 290
Element 30 is 300
Element 31 is 310
Element 32 is 320
Element 33 is 330
Element 34 is 340
Element 35 is 350
Element 36 is 360
Element 37 is 370
Element 38 is 380
Element 39 is 390
Element 40 is 400
Element 41 is 410
Element 42 is 420
Element 43 is 430
Element 44 is 440
Element 45 is 450
Element 46 is 460
Element 47 is 470
Element 48 is 480
Element 49 is 490
Element 50 is 500
Element 51 is 510
Element 52 is 520
Element 53 is 530
Element 54 is 540
Element 55 is 550
Element 56 is 560
Element 57 is 570
Element 58 is 580
Element 59 is 590
Element 60 is 600
Element 61 is 610
Element 62 is 620
Element 63 is 630
Element 64 is 640
Element 65 is 650
Element 66 is 660
Element 67 is 670
Element 68 is 680
Element 69 is 690
Element 70 is 700
Element 71 is 710
Element 72 is 720
Element 73 is 730
Element 74 is 740
Element 75 is 750
Element 76 is 760
Element 77 is 770
Element 78 is 780
Element 79 is 790
Element 80 is 800
Element 81 is 810
Element 82 is 820
Element 83 is 830
Element 84 is 840
Element 85 is 850
Element 86 is 860
Element 87 is 870
Element 88 is 880
Element 89 is 890
Element 90 is 900
Element 91 is 910
Element 92 is 920
Element 93 is 930
Element 94 is 940
Element 95 is 950
Element 96 is 960
Element 97 is 970
Element 98 is 980
Element 99 is 990

Example 8.12, Page Number 343

In [12]:
LIMIT = 100

class safearay:
    __arr = [0 for j in range(LIMIT)]
    
    def op1(self,n,n1):                  #function for set the value in the array 
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        self.__arr[n] = n1
        
    def op2(self,n):                     #function for return the array
        if n<0 or n>=LIMIT:
            print 'Index out of bound'
        return self.__arr[n]
    
    
    
sa1 = safearay()

for j in range(LIMIT):                       #insert elements using first function
    sa1.op1(j,j*10)
    
for j in range(LIMIT):                       #display elements using second function
    temp = sa1.op2(j)
    print 'Element',j,'is',temp
Element 0 is 0
Element 1 is 10
Element 2 is 20
Element 3 is 30
Element 4 is 40
Element 5 is 50
Element 6 is 60
Element 7 is 70
Element 8 is 80
Element 9 is 90
Element 10 is 100
Element 11 is 110
Element 12 is 120
Element 13 is 130
Element 14 is 140
Element 15 is 150
Element 16 is 160
Element 17 is 170
Element 18 is 180
Element 19 is 190
Element 20 is 200
Element 21 is 210
Element 22 is 220
Element 23 is 230
Element 24 is 240
Element 25 is 250
Element 26 is 260
Element 27 is 270
Element 28 is 280
Element 29 is 290
Element 30 is 300
Element 31 is 310
Element 32 is 320
Element 33 is 330
Element 34 is 340
Element 35 is 350
Element 36 is 360
Element 37 is 370
Element 38 is 380
Element 39 is 390
Element 40 is 400
Element 41 is 410
Element 42 is 420
Element 43 is 430
Element 44 is 440
Element 45 is 450
Element 46 is 460
Element 47 is 470
Element 48 is 480
Element 49 is 490
Element 50 is 500
Element 51 is 510
Element 52 is 520
Element 53 is 530
Element 54 is 540
Element 55 is 550
Element 56 is 560
Element 57 is 570
Element 58 is 580
Element 59 is 590
Element 60 is 600
Element 61 is 610
Element 62 is 620
Element 63 is 630
Element 64 is 640
Element 65 is 650
Element 66 is 660
Element 67 is 670
Element 68 is 680
Element 69 is 690
Element 70 is 700
Element 71 is 710
Element 72 is 720
Element 73 is 730
Element 74 is 740
Element 75 is 750
Element 76 is 760
Element 77 is 770
Element 78 is 780
Element 79 is 790
Element 80 is 800
Element 81 is 810
Element 82 is 820
Element 83 is 830
Element 84 is 840
Element 85 is 850
Element 86 is 860
Element 87 is 870
Element 88 is 880
Element 89 is 890
Element 90 is 900
Element 91 is 910
Element 92 is 920
Element 93 is 930
Element 94 is 940
Element 95 is 950
Element 96 is 960
Element 97 is 970
Element 98 is 980
Element 99 is 990

Example 8.13, Page Number 345

In [13]:
class Distance:                                              #class Distance
    
    def __init__(self,meters=None,ft=0,inc=0.0):             #constructor
        
        if isinstance(meters,float):                         #one argument 
            self.__MTF = 3.280833                            #convert meters to Distance,
            fltfeet = self.__MTF*meters                      #convert to float feet
            self.__feet = int(fltfeet)                       #feet is integer part
            self.__inches = 12*(fltfeet-self.__feet)         #inches is what's left
            
        else:                                                #three arguments (first should be None)
            self.__MTF = 3.280833
            self.__feet = ft
            self.__inches = inc
        
        
    def getdist(self):                                       #get length from user
        self.__feet = input("Enter feet: ")
        self.__inches = input("Enter inches: ")
        
    def showdist(self):                                      #display Distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
    def co(self):                               #conversion function, converts Distance to meters
        fracfeet = self.__inches/12             #convert the inches
        fracfeet += float(self.__feet)          #add the feet
        return fracfeet/self.__MTF              #convert to meters
    
    
    
dist1 = Distance(2.35)                          #uses 1-arg constructor to convert meters to Distance
print 'dist1 =',; dist1.showdist()

mtrs = dist1.co()                               #uses conversion function for Distance to meters
print 'dist1 =',mtrs,'meters'
   
dist2 = Distance(None,5,10.25)                  #uses 2-arg constructor
mtrs = dist2.co()                               #also uses conversion function
print 'dist2 =',mtrs,'meters'
dist1 = 7 ' - 8.5194906 "
dist1 = 2.35 meters
dist2 = 1.78435375 meters

Example 8.14, Page Number 348

In [14]:
class String:                            #user-defined string type
    __SZ = 80                            #size of all String type
    
    def __init__(self,s = None):         #constructor with zero or one argument
        self.__str = s
        
    def display(self):                   #display the String
        print self.__str,
    
    def char(self):                      #conversion function
        return self.__str
    
    
    
xstr = "Joyeux Noel! "

s1 = String(xstr)                       #use 1-arg constructor
s1.display()                            #display string

s2 = String("Bonne Annee!")             #use 1-arg constructor to initialize string
print s2.char()                         #uses conversion fuction
Joyeux Noel!  Bonne Annee!

Example 8.15, Page Number 351

In [15]:
class time12:
    
    def __init__(self,ap=True,h=0,m=0):              #constructor
        self.__pm = ap                               #true = pm, false = am
        self.__hrs = h                               # 1 to 12
        self.__mins = m                              # 0 to 59
        
    def display(self):                               #format: 11:59 p.m.
        print self.__hrs,':',
        
        if self.__mins < 10:
            print '0',                               #extra zero for "01"
            
        print self.__mins,
        
        if self.__pm:
            print 'p.m.'
        else:
            print 'a.m.'
            
            
            
class time24:
    
    def __init__(self,h=0,m=0,s=0):                  #constructor
        self.__hours = h                             # 0 to 23
        self.__minutes = m                           # 0 to 59
        self.__seconds = s                           # 0 to 59
         
    def display(self):                               #format: 23:15:01
        if self.__hours < 10:
            print '0',
        print self.__hours,':',
        
        if self.__minutes < 10:
            print '0',
        print self.__minutes,':',
        
        if self.__seconds < 10:
            print '0',
        print self.__seconds
        
        
    def time_12(self):                               #conversion from 24-hour time to 12-hour time
        
        hrs24 = self.__hours
        if self.__hours < 12:                        #find am/pm
            pm = False
        else:
            pm = True
            
        if self.__seconds < 30:                      #round secs
            roundMins = self.__minutes
        else:
            roundMins = self.__minutes + 1
            
        if roundMins == 60:                          #carry mins?
            roundMins = 0
            hrs24 += 1
            if hrs24 == 12 or hrs24 == 24:           #carry hrs?
                if pm == True:                       #toggle am/pm
                    pm = False
                else:
                    pm = True
        
        if hrs24 < 13:
            hrs12 = hrs24
        else:
            hrs12 = hrs24-12
            
        if hrs12 == 0:                               # 00 is 12 a.m.
            hrs12 = 12
            pm = False
            
        return time12(pm,hrs12,roundMins)
    
    
    
while True:
    
    print '\nEnter 24-hour time: '
    h = input("   Hours (0 to 23): ")                #get 24-hr time from user
    
    if h > 23:                                       #quit if hours > 23
        break
        
    m = input("   Minutes: ")  
    s = input("   Seconds: ")
        
    t24 = time24(h,m,s)                          #make a time24
    print 'You entered:',
    t24.display()                                #display the time24
         
    t12 = t24.time_12()                          #convert time24 to time12
        
    print '12-hour time:',                       #display equivalent time12
    t12.display()
Enter 24-hour time: 
   Hours (0 to 23): 17
   Minutes: 59
   Seconds: 45
You entered: 17 : 59 : 45
12-hour time: 6 : 0 0 p.m.

Enter 24-hour time: 
   Hours (0 to 23): 24

Example 8.16, Page Number 354

In [16]:
class time24:
    
    def __init__(self,h=0,m=0,s=0):                  #constructor
        self.__hours = h                             # 0 to 23
        self.__minutes = m                           # 0 to 59
        self.__seconds = s                           # 0 to 59
         
    def display(self):                               #format: 23:15:01
        if self.__hours < 10:
            print '0',
        print self.__hours,':',
        
        if self.__minutes < 10:
            print '0',
        print self.__minutes,':',
        
        if self.__seconds < 10:
            print '0',
        print self.__seconds
        
    def getHrs(self):
        return self.__hours
    def getMins(self):
        return self.__minutes
    def getSecs(self):
        return self.__seconds
    
    
class time12:
    
    def __init__(self,ap=True,h=0,m=0):              #constructor
        
        if isinstance(ap,bool):
            self.__pm = ap                               #true = pm, false = am
            self.__hrs = h                               # 1 to 12
            self.__mins = m                              # 0 to 59
            
        else:                                           #conversion from 24-hour time to 12-hour time
            t24 = ap
            
            hrs24 = t24.getHrs()
            
            if t24.getHrs() < 12:                        #find am/pm
                self.__pm = False
            else:
                self.__pm = True
            
            if t24.getSecs() < 30:                      #round secs
                self.__mins = t24.getMins()
            else:
                self.__mins = t24.getMins() + 1
            
            if self.__mins == 60:                          #carry mins?
                self.__mins = 0
                hrs24 += 1
                
                if hrs24 == 12 or hrs24 == 24:           #carry hrs?
                    if self.__pm == True:                       #toggle am/pm
                        self.__pm = False
                    else:
                        self.__pm = True
        
            if hrs24 < 13:
                self.__hrs = hrs24
            else:
                self.__hrs = hrs24-12
            
            if self.__hrs == 0:                               # 00 is 12 a.m.
                self.__hrs = 12
                self.__pm = False
        
    def display(self):                               #format: 11:59 p.m.
        print self.__hrs,':',
        
        if self.__mins < 10:
            print '0',                               #extra zero for "01"
        print self.__mins,
        
        if self.__pm:
            print 'p.m.'
        else:
            print 'a.m.'
            
            
            
while True:
    
    print '\nEnter 24-hour time: '
    h = input("   Hours (0 to 23): ")                #get 24-hr time from user
    
    if h > 23:                                       #quit if hours > 23
        break
        
    m = input("   Minutes: ")  
    s = input("   Seconds: ")
        
    t24 = time24(h,m,s)                          #make a time24
    print 'You entered:',
    t24.display()                                #display the time24
         
    t12 = time12(t24)                          #convert time24 to time12
        
    print '12-hour time:',                       #display equivalent time12
    t12.display()
Enter 24-hour time: 
   Hours (0 to 23): 17
   Minutes: 59
   Seconds: 45
You entered: 17 : 59 : 45
12-hour time: 6 : 0 0 p.m.

Enter 24-hour time: 
   Hours (0 to 23): 25

Example 8.17, Page Number 360

In [17]:
class Distance:                                              #class Distance
    
    def __init__(self,meters=None,ft=0,inc=0.0):             #constructor
        
        if isinstance(meters,float):                         #one argument 
            self.__MTF = 3.280833                            #convert meters to Distance,
            fltfeet = self.__MTF*meters                      #convert to float feet
            self.__feet = int(fltfeet)                       #feet is integer part
            self.__inches = 12*(fltfeet-self.__feet)         #inches is what's left
            
        else:                                                #three arguments (first should be None)
            self.__MTF = 3.280833
            self.__feet = ft
            self.__inches = inc
            
            
    def showdist(self):                                      #display Distance
        print self.__feet , '\' -' , self.__inches , '\"'
        
        
        
def fancyDist(d):
    print '(in feet and inches) =',
    d.showdist()
    
    

dist1 = Distance(2.35)
print 'dist1 =',; dist1.showdist()

mtrs = 3.0
print 'dist1'
dist1 = 7 ' - 8.5194906 "
dist1

Example 8.18, Page Number 363

In [18]:
class scrollbar:
    
    def __init__(self,sz,own):               #constructor
        self.__size = sz
        self.__owner = own
        
    def setSize(self,sz):                    #change size
        self.__size = sz
        
    def setOwner(self,own):                  #change owner
        self.__owner = own
        
    def getSize(self):                       #returns size
        return self.__size
    
    def getOwner(self):                      #returns owner
        return self.__owner
    
    
    
sbar = scrollbar(60,"Window1")

sbar.setOwner("Window2")

print sbar.getSize(),', ',sbar.getOwner()
60 ,  Window2
In [ ]: