[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

objects effectively serve the roles of both database records and database-processing
programs. We can also use the underlying pickle module to serialize instances to flat
files and other file-like objects (e.g., network sockets), but the higher-level shelve mod-
ule also gives us a convenient keyed-access storage medium. For instance, consider the
simple class shown in Example 17-2, which is used to model people in a hypothetical
work scenario.


Example 17-2. PP4E\Dbase\person.py (version 1)


"a person object: fields + behavior"


class Person:
def init(self, name, job, pay=0):
self.name = name
self.job = job
self.pay = pay # real instance data
def tax(self):
return self.pay * 0.25 # computed on call
def info(self):
return self.name, self.job, self.pay, self.tax()


Nothing about this class suggests it will be used for database records—it can be im-
ported and used independent of external storage. It’s easy to use it for a database’s
records, though: we can make some persistent objects from this class by simply creating
instances as usual, and then storing them by key on an opened shelve:


C:\...\PP4E\Dbase> python
>>> from person import Person
>>> bob = Person('bob', 'psychologist', 70000)
>>> emily = Person('emily', 'teacher', 40000)
>>>
>>> import shelve
>>> dbase = shelve.open('cast') # make new shelve
>>> for obj in (bob, emily): # store objects
... dbase[obj.name] = obj # use name for key
...
>>> dbase.close() # need for bsddb

Here we used the instance objects’ name attribute as their key in the shelve database.
When we come back and fetch these objects in a later Python session or script, they
are re-created in memory exactly as they were when they were stored:


C:\...\PP4E\Dbase> python
>>> import shelve
>>> dbase = shelve.open('cast') # reopen shelve
>>>
>>> list(dbase.keys()) # both objects are here
['bob', 'emily']
>>> print(dbase['emily'])
<person.Person object at 0x0197EF70>
>>>
>>> print(dbase['bob'].tax()) # call: bob's tax
17500.0

Shelve Files | 1319
Free download pdf