## more oop examples: # metrocard: class metrocard: def __init__(self,initval): self.value = initval self.price = 2.5 # $2.50 per ride # constructor def ride(self): # take one ride if self.value>=self.price: self.value -= self.price return "please watch the gap between the train and the platform" else: return "not enough funds" # ride def refill(self,amt): # refill card, $1 credit for every 10 dollars self.value += amt if (amt>=10): self.value += int(amt) / 10 # refill def check(self): # check current balance: return self.value # check def renew(self): # transfer balance to a new card newcard = metrocard(self.value) self.value = 0 return newcard # renew #metrocard mycard = metrocard(20) card2 = metrocard(15) print mycard.ride() print "your current value is ", mycard.check() mycard2 = mycard.renew() print mycard.ride() print mycard2.ride() mycard.refill(25) #### minutes and seconds class time: def __init__(self,m,s): # constructor sets intial time self.min = m self.sec = s # __init__ def reset(self): self.min, self.sec = 0,0 #reset # destructive addition of minutes and seconds: def add(self,m,s): tsec = self.sec + s self.min += m + (tsec/60) self.sec = tsec % 60 #time # version of add that accepts one additional parameter: def sum(self,other): tsec = self.sec + other.sec self.min += other.min + (tsec/60) self.sec = tsec % 60 # sum # non-destructive version of add, returns a new time object: def cadd(self,other): tsec = self.sec + other.sec m = self.min + other.min + (tsec/60) s = tsec % 60 newtime = time(m,s) return newtime # constructive addition ### defining a function in terms of other functions def tick(self): # destructive increase of one second self.add(0,1) # tick def equals(self,other): return self.min == other.min and self.sec == other.sec # == : recommend against overloading __eq__ ### OPERATOR OVERLOADING: def __add__(self,other): # overloads + tsec = self.sec + other.sec m = self.min + other.min + (tsec/60) s = tsec % 60 newtime = time(m,s) return newtime # constructive addition def __cmp__(self,other): # overloads ==, <, >=, etc ... sec1 = self.min*60 + self.sec sec2 = other.min*60 + other.sec return sec1-sec2 # cmp returns negative if selfother, 0 otherwise def tostring(self): return str(self.min)+"m"+str(self.sec)+"s" # tostring # time t1 = time(1,30) t2 = time(2,45) t1.add(0,3) t2.sum(t1) t3 = t1.cadd(t2) t2.tick() t4 = t1 + t2 # using __add__ implicitly print t1.tostring() print t2.tostring() print t3.tostring() print t4.tostring() t5 = time(1,33) print t1, t5 print (t1 == t5) # false without operator overloading! print t1.equals(t5) print t1 <= t5