Perl vs. Python question...

Lloyd Kvam python at venix.com
Mon Jul 13 11:19:30 EDT 2009


On Sat, 2009-07-11 at 23:44 -0400, Paul Lussier wrote:
> How do I create dynamically created methods in python classes?
> 
> For example, if I have a number of member variables which I want to
> get
> or set, I don't want to have to create getters and setters for each
> attribute, since the code would largely be the same, just the variable
> I'm dealing with would be different.

You've already gotten two useful responses.  I'd just like to add that
typically, the object attributes are referenced directly:
        rect.length * rect.width
to compute area.  Do not use: rect.get_length() * rect.get_width().

getter/setter methods get created when you some code is needed to
control access:
        room.celsius
        room.fahrenheit
computes the proper value from a single stored temperature (in Kelvin?).
The code still looks like a direct reference to the attribute.  You have
a choice of using __getattr__/__getattribute__/__setattr__ 
or properties as suggested in the other email responses.

-- 
Lloyd Kvam
Venix Corp
DLSLUG/GNHLUG library
http://dlslug.org/library.html
http://www.librarything.com/catalog/dlslug
http://www.librarything.com/rsshtml/recent/dlslug
http://www.librarything.com/rss/recent/dlslug



More information about the gnhlug-discuss mailing list