[Tutor] Public, private and protected member variables.
Lloyd Kvam
pythontutor at venix.com
Tue Oct 21 10:36:32 EDT 2003
Marc Barry wrote:
> I do find myself using a lot of setFoo and getFoo. I
> too would like to better understand how to design
> classes to get around this problem. Right now, I have
> a class that I reuse in many different situations and
> depending on the situation the class requires
> different properties. Basically, what I have done is I
> use a dictionary inside the class that uses a string
> as the key and any object as a value. Therefore, I
> have methods of the form:
>
> setProperty(key, value)
> getProperty(key)
>
> I cannot come up with a better way to design the class
> to avoid using these types of accessor functions. I
> hear many comments that this type of design is ugly
> and lots of people hate getFoo/setFoo, but I guess I
> can't seem to find a better way to handle the type of
> situation where you have an object that has different
> properties depending on the situation it is used.
>
Python has built in functions getattr(obj, key) and setattr(obj,key,value)
that are generic equivalents to the get/setProperty methods except that
you must supply the object.
If the property names are known when you are writing your code, you can simply
create attributes in a class by assigning to the attribute name:
some_obj.foo = "some value"
The object: some_obj now has a new attribute: foo.
I have a "generic" class for dealing with database tables. When connected to
a specific database table, the list of fieldnames are determined and stored
with the class. The __setattr__ method verifies attribute names are valid
for this table and keeps a list of changed attributes for INSERTs and UPDATEs.
The __getattr__ method will catch references to database fields that are not yet
assigned/defined and return None. For other attribute names it raises an
AttributeError.
If it is necessary to enforce some consistancy between fields,
e.g. startdate < enddate, this can be done in the __setattr__ method.
(Most of these ideas were borrowed from examples in Python Programming
on Win32)
The good side of this approach:
easy to read object references (obj.attribute)
reasonable enforcement of object requirements
fewer methods to write
The bad side:
__setattr__ can become complex to maintain
encourages habit of direct manipulation of attributes
Once I start grabbing attributes, I can go overboard. A simple example:
build a formatted string for a customer record by writing code that grabs
cust.firstname and cust.lastname and so on. The better approach is to have a
customer method that returns the formatted string. Then the logic is written once
and placed where you would expect to find it.
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582
More information about the Tutor
mailing list