您的位置:首页 > 编程语言 > Python开发

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

2014-08-26 15:44 417 查看
一个慢慢学习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__)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: