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

(yzsuai) #1

except:
print('No such key "%s"!' % key)
else:
for field in fieldnames:
print(field.ljust(maxfield), '=>', getattr(record, field))


This script uses the getattr built-in function to fetch an object’s attribute when given
its name string, and the ljust left-justify method of strings to align outputs (max
field, derived from a generator expression, is the length of the longest field name).
When run, this script goes into a loop, inputting keys from the interactive user (tech-
nically, from the standard input stream, which is usually a console window) and dis-
playing the fetched records field by field. An empty line ends the session. If our shelve
of class instances is still in the state we left it near the end of the last section:


...\PP4E\Preview> dump_db_classes.py
bob =>
Bob Smith 30000
sue =>
Sue Jones 50000.0
tom =>
Tom Doe 65000.0
Smith
Doe

We can then use our new script to query the object database interactively, by key:


...\PP4E\Preview> peopleinteract_query.py

Key? => sue
name => Sue Jones
age => 45
job => hardware
pay => 50000.0

Key? => nobody
No such key "nobody"!

Key? =>

Example 1-22 goes further and allows interactive updates. For an input key, it inputs
values for each field and either updates an existing record or creates a new object and
stores it under the key.


Example 1-22. PP4E\Preview\peopleinteract_update.py


interactive updates


import shelve
from person import Person
fieldnames = ('name', 'age', 'job', 'pay')


db = shelve.open('class-shelve')
while True:
key = input('\nKey? => ')
if not key: break


38 | Chapter 1: A Sneak Preview

Free download pdf