use class factory to set required class variables?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 27 04:03:29 EST 2011


On Wed, 26 Jan 2011 13:37:20 -0800, Alan wrote:

> I have a class ``A`` that is intentionally incomplete: it has methods
> that refer to class variables that do not exist. 

For the record, in Python it is usual to refer to "attributes" rather 
than "class variables" and "instance variables". In Python, classes are 
first-class objects (pun not intended) like ints, strings, floats etc., 
and so a "class variable" would be a variable holding a class, just as a 
string variable would be a variable holding a string, an int variable 
holds an int, etc.


> The class ``A`` has
> several complicated methods, a number of which reference the "missing"
> class variables. Obviously, I do not directly use ``A``.

This is called an abstract class -- you need to subclass it to use it.


> I have a class factory ``f``` that subclasses ``A`` *only* in order to
> define the class variables.
> 
> The motivation/problem:
> I did this because I need many versions of class ``A``, which differ
> only in the class variables, which are not known until run time.
> 
> Q: On the face of it, did I pick a reasonable solution to my problem? 
> If so is this a standard pattern?  If not, can you mention a better
> approach?

You have a class factory which subclasses an abstract class. Seems 
perfectly reasonable to me. More than reasonable -- it sounds like a 
*good* way of dealing with the problem.




-- 
Steven



More information about the Python-list mailing list