Programming Python - 1. Preview -1.3 Stepping up to OOP
OOP: Structure, Encapsulation, Customization
1. Using Classes
class Person: def __init__(self, name, age, pay=0, job=None): self.name=name self.age=age self.pay=pay self.job=job if __name__=='__main__': bob=Person('bob smith', 42, 30000, 'software') sue=Person('sue jones',45, 45000,'hareware') print(bob.name, sue.pay) print(bob.name.split()[-1]) sue.pay *= 1.1 print(sue.pay)
2. Adding Behavior
#class Person class Person: def __init__(self, name, age, pay=0, job=None): self.name=name self.age=age self.pay=pay self.job=job def lastname(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1+percent) if __name__=="__main__": bob=Person('bob smith', 42, 30000, 'software') sue=Person('sue jones', 45, 50000, 'hardware') print(bob.name, sue.pay) print(bob.lastname()) sue.giveRaise(0.1) print(sue.pay)
Adding Inheritance
from person import Person class Manager(Person): def giveRaise(self, percent, bonus=0.1): self.pay*=(1+percent+bonus) if __name__=='__main__': tom=Manager(name='tom doe', age=50, pay=50000) print(tom.lastname()) tom.giveRaise(0.2) print( tom.pay)
Alternative implementation
class Person: def __init__(self, name, age, pay=0, job=None): self.name=name self.age=age self.pay=pay self.job=job def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1+percent) def __str__(self): return ('%s => %s: %s, %s' % (self.__class__.__name__, self.name, self.job, self.pay)) class Manager(Person): def __init__(self, name, age, pay): Person.__init__(self, name,age, pay, 'Manager') def giveRaise(self, percent, bonus=0.1): Person.giveRaise(self, percent+bonus) if __name__=='__main__': bob=Person('bob smith', 44) sue=Person('sue jones', 47, 40000, 'manager') tom=Manager(name='tom doe', age=50, pay=50000) print(sue, sue.pay, sue.lastName) for obj in (bob, sue, tom): obj.giveRaise(0.1) print(obj)
Adding Persistence
#make_db_classes import shelve from person import Person from manager import Manager bob=Person('bob smith', 42, 3000, 'software') sue=Person('sue jones', 45, 4000, 'hardware') tom=Manager('tom doe', 50, 5000) db=shelve.open('class-shelve') db['bob']=bob db['sue']=sue db['tom']=tom db.close()
#dump_db_classes import shelve db=shelve.open('class-shelve') for key in db: print(key, '=>\n', db[key].name, db[key].pay) bob=db['bob'] print(bob.lastname()) print(db['tom'].lastname)
#update_db_classes import shelve db=shelve.open('class-shelve') sue=db['sue'] sue.giveRaise(.25) db['sue']=sue tom=db['tom'] tom.giveRaise(.20) db['tom']=tom db.close()