[Tutor] Public, private and protected member variables.

Alan Gauld alan.gauld at blueyonder.co.uk
Tue Oct 21 17:46:09 EDT 2003


> 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. 

In that case they are different classes. Although Python 
allows you to add properties (aka attributes) at run time
this probably is the wrong way to tackle it here.

Is the interface constant between the classes - in other 
words are the multitude of classes polymorphic? If so 
then use inheritance to define the classes you need.
(and if not then they are definitely different classes!)

If you don't know which class you need until runtime 
build a factory method(or class!) that will look at the 
context and return an instance of the right variation.

> use a dictionary inside the class that uses a string
> as the key and any object as a value. 

Thats how Python builds a class internally, you are 
duplicating Python's work...

> setProperty(key, value)
> getProperty(key)

Which is what the getattr and setattr methods do internally 
in Python...

> I cannot come up with a better way to design the class
> to avoid using these types of accessor functions. 

What is the class doing? What data does it manage and 
what needs to be done to that data? And whatever it is 
a method of the class should do it.

> 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.

By definition those are different classes. An class is 
defined by its identity, state values and behaviour. 
By having different sets of state variables you are 
effectively changing the class! You are just doing it 
at run time!

Without more details on what the design looks like and 
what you are trying to achieve its impossible to be 
more specific. However generally this situation is handled 
by creating a class heirarchy(eg a UI event heirarchy) 
or by creating a generic data carrier collection class
(a bit like your dictionary) that is itself an attribute 
of the dynamic object. This latter solution can be messy 
and is only normally done when the multi class approach 
leads to an explosion in the number of classes (over a 
dozen say). But if you are currently managing it by adding 
attributes in code then I'd guess creating a class tree is
not going to be unreasonable.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list