I am reading through Lutz's Programming Python and the following script is designed to create three records of people, make them persistent by storing them in a shelve, and then allow a user to enter people names in the terminal to get information back. I don't have all the code here, just what I think is necessary to understand.
Lines 8-13 show the class used in creating each person. These are then written to a shelf called class-shelve shown on line 15. The two lines I'm having trouble understanding are 17 and 29/30.
17 I am not sure of the logic here.
29 is the line from the book, and I don't understand how the code i try on 30 is any different?
6 import shelve
7
8 class Person:
9 def __init__(self, name, age, pay=0, job=None):
10 self.name = name
11 self.age = age
12 self.pay = pay
13 self.job = job
14
15 classShelve = './output/class-shelve'
16 fieldnames = ('name', 'age', 'job', 'pay')
17 maxfield = max(len(f) for f in fieldnames)
18 db = shelve.open(classShelve)
19
20 while True:
21 key = input('\nKey? => ')
22 if not key: break
23 try:
24 record = db[key]
25 except:
26 print('No such key "%s"!' % key)
27 else:
28 for field in fieldnames:
29 #print(field.ljust(maxfield), '=>', getattr(record, field))
30 print(field, '=>', getattr(record, field))
max(len(f) for f in fieldnames)=> the max len(gth) of f for (all of the) f in fieldnames. For 29 v 30, there isn't really a difference, except the use of ljust. Is that your question?'hello'.ljust(5)and'hello'.ljust(20)(note all the trailing space after the latter, or use rjust if it's easier to see).