一个慢慢学习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__)
本文介绍了一个Python类的实用示例,展示了如何利用自定义类实现对象属性的显示,并通过Shelve模块进行对象持久化存储。代码示例包括一个AttrDisplay类用于格式化输出实例属性,以及Person和Manager子类的创建与属性更新。此外,还演示了如何将这些对象存储到Shelve数据库中并从中读取。
2849

被折叠的 条评论
为什么被折叠?



