Fwd: RE: [Tutor] while with function

Magnus Lycka magnus@thinkware.se
Tue Nov 19 17:14:49 2002


>From: <fleet@teachout.org>
>Ok.  I fixed the EDITOR problem.  But I still don't know how I'm supposed
>use this.

As I understood your application, you have a number of
parameters, and you should be able to enter new data
as well as update existing data. Below is an example
of how my edit module could be used.

Save the code below to a file called edittest.py, and
make sure that the previous edit.py is in the same directory.
Then:

$ python -i edittest.py
 >>> p = Person()
 >>> p.edit()
# Now you are inside your editor. Write some nice values
# after the colons and save and quit. (ZZ in vi)
 >>> print p
# Now you should see what you wrote. Oops, you misspelled
# a surname.
 >>> p.edit()
# You see all the previously entered values. Correct what
# needs to be corrected. Save and quit.
 >>> print p
# Nice, it seems right now.
# Are these really normal parameters?
 >>> print p.firstName
 >>> print p.phone
# So it seems...

If you like, you could use the edit module so that you list
and permit editing of many, maybe all, your database values
at once. Maybe you want to search and replace an area code
for telephone numbers. Just use the normal editor features!
You have all the editing features at your disposal. If you
mess up, quit without saving, and you're back where you
started. Isn't this better than raw_input?

I hope te use of getattr and setattr below isn't too confusing.
Basically getattr(a,'x') is the same as a.x, and a.y = 5 is
the same as setattr(a, 'y', 5). Using getattr and setattr, it's
easy to keep as list (_params) that tells which attributes we
want to be able to edit and in what order to present and edit
them, without all too much repetetive code. If we imagine several
classes with different types of parameters, we could use the
methods below in a base class, and then just change the class
attribute _params in each derivate class. Nice, isn't it?

#########################
import edit

class Person:
     _params = ['firstName', 'lastName', 'phone', 'email']

     def edit(self):
         data = []
         for param in self._params:
             if hasattr(self, param):
                 value = getattr(self, param)
             else:
                 value = ""
             data.append((param, value))
         data = edit.edit(data)
         for param, value in data:
             if param in self._params:
                 setattr(self, param, value)

     def __str__(self):
         data = []
         for param in self._params:
             if hasattr(self, param):
                 value = getattr(self, param)
             else:
                 value = ""
             data.append("%s = %s" % (param, value))
         return "\n".join(data)



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se