[Tutor] get/set attributes

Eric Abrahamsen eric at ericabrahamsen.net
Sun May 25 12:30:28 CEST 2008


Hello,

I'm trying to create a Dummy class of objects, something that will  
return an empty string for any attribute. I'm making a very simple CMS  
with Cherrypy/Sqlalchemy/Cheetah, and I have an HTML form template  
that I use for editing/creating objects to save to the database. I'm  
using just one form template, and I want to either pass an object from  
the database to the template (for editing existing objects), or a  
Dummy object which outputs empty strings for all the HTML form fields,  
creating a blank form. Additionally, I'd like to be able to pass  
keyword arguments to the Dummy() initialization which get turned into  
attributes, so I can output various default values for the form fields.

What I've got so far handles non-existent attributes fine, but using  
keywords to create attributes isn't working (attributes thus set still  
output an empty string), and I'm not sure why. Here's the class:

class Dummy(object):
     def __init__(self,**atts):
         for k,v in atts.items():
             self.k = v

     def __repr__(self):
         return ''

     def __getattr__(self, attr):
         return ''

 >>> dum = Dummy(name='John')
 >>> dum

 >>> dum.nationality
''
 >>> dum.name
''

__getattr__ says it only comes into play when an attribute is NOT  
found, so I must be doing something wrong in the __init__ method...

Thanks in advance,
Eric


More information about the Tutor mailing list