【Python学习手册】类学习,以及shelve使用

一个慢慢学习python类和shelve存储文件的使用例子。


#!/bin/env python
#-*- coding:utf-8 -*-
#<span style="font-family: Arial, Helvetica, sans-serif;">classtools.py</span>
#
"Assorted class Utilities and tools"
class AttrDisplay:
    """
    Provide an inheritable print overloadmethod that displays
    instances with their class names and a name=value pair for 
    each attribute stored on the instance itself(but not attrs 
    inherited from its classes). Can be mixed into any class, and
    will work on any instance.
    """
    def gatherAttrs(self):
        attrs=[]
        for key in sorted(self.__dict__):
            attrs.append('%s=%s' % (key, getattr(self, key)))
        return ', '.join(attrs)
    def __str__(self):
        return '[%s: %s]' % (self.__class__.__name__, self.gatherAttrs())
    
if __name__ == '__main__':
    class TopTest(AttrDisplay):
        count=0
        def __init__(self):
            self.attr1 = TopTest.count
            self.attr2 = TopTest.count+1
            TopTest.count+=2
    class SubTest(TopTest):
        pass
    X,Y=TopTest(),SubTest()
    print(X)
    print(Y)
    
    from person import Person
    bob=Person('Bob Smith')
    print(bob.__dict__.keys())
    print(dir(bob))
    print(list(bob.__dict__.keys()))
    print(dir(bob))


#!/bin/env python
#-*- coding:utf-8 -*-
#makedb.py
#
import shelve
from person import Person, Manager
bob=Person('Bob Smith')
sue=Person("Sue Jones",job='Dev', pay=100000)
tom=Manager('Tom Jones', 50000)

#写入DB
def WriteDB():
    db=shelve.open('persondb')
    for object in (bob,sue,tom):
        db[object.name]=object
    db.close()

#读取方法
def ReadDB():
    db=shelve.open('persondb')
    print("Len DB %d:" % len(db))
    print("List DB Keys ",list(db.keys()))
    bob=db['Bob Smith']
    print(bob)
    for key in db:
        print(key,'\t=>',db[key])
    db.close()
def UpdateDB():
    db=shelve.open('persondb')
    for key in sorted(db):
        print(key, '\t=>', db[key])
        
        sue=db['Sue Jones']
        sue.giveRaise(.10)
        db['Sue Jones']=sue    
    db.close()
    
if __name__ == '__main__':
    WriteDB()
    import glob
    print(glob.glob('person*'))
    print(open('persondb.dat','rb').read())
    
    print(glob.glob('*'))
    print("============DB Read====================") 
    ReadDB()
    print("\n============DB Update==================")
    UpdateDB()
    print("\n============DB Read====================")   
    ReadDB()

#!/bin/env python
#-*- coding:utf-8 -*-
#person.py
#
from classtools import AttrDisplay

class Person(AttrDisplay):
    def __init__(self, name, job=None, pay=0):
        self.name = name
        self.job = job
        self.pay = pay
    def lastName(self):
        return self.name.split()[-1]
    def giveRaise(self,percent):
        self.pay=int(self.pay*(1+percent))
    #def __str__(self): #如果再次定义该函数,则会替代AttrDisplay中的__str__函数
        #return '[Person: %s, %s]' % (self.name, self.pay)
    
class Manager(Person):
    def __init__(self, name, pay):
        Person.__init__(self,name,'mgr', pay)
    def giveRaise(self,percent,bonus=.10):
        self.pay=int(self.pay*(1+percent+bonus))
    
class Department:
    def __init__(self, *args):
        self.members = list(args)
    def addMember(self, person):
        self.members.append(person)
    def giveRaise(self,percent):
        for person in self.members:
            person.giveRaise(percent)
    def showAll(self):
        for person in self.members:
            print(person)
            
if(__name__=="__main__"):
    bob=Person('Bob Smith')
    sue=Person('Sue Jones', job='dev', pay=1000000)
    sue.giveRaise(.10)
    Jackie=Manager("Jackie",110000)
    Jackie.giveRaise(.10)
    
    print('\n---All Three---')
    for per in (bob,sue,Jackie):
        per.giveRaise(.10)
        print(per)
    print('\n---All Development---')
    development=Department(bob, sue)
    development.addMember(Jackie)
    development.giveRaise(.10)
    development.showAll()
    print('\n---All Other---')
    print("Bob's Class Name: %s" % bob.__class__.__name__)
    print("Jackie's Class Name: %s" % Jackie.__class__.__name__)
    
    








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值