use class factory to set required class variables?

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Jan 27 05:15:37 EST 2011


Alan wrote:
> I have a class ``A`` that is intentionally incomplete:
> it has methods that refer to class variables that do not exist.
> The class ``A`` has several complicated methods, a number
> of which reference the "missing" class variables.
> Obviously, I do not directly use ``A``.
>
> 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?
>
> My solution is working for me, but the class ``A``
> is bugging me, because of the odd (to me) way in
> which it is incomplete.  Obviously, I'm not a
> computer science type ...
>
> Thanks,
> Alan Isaac
>
>   
Your design is perfectly fine. A is an abstract class, aka interface class.
This is a very common pattern, that can solve many problems.

However, and this is a personal advice, try to declare all the required 
attributes/methods in the abstract class, setting them to None or 
raising a NotImplementedError. That would help anyone, including you, to 
know what is required to define when subclassing A.

class A:
    A_VALUE = None
    def aMethod(self):
       raise NotImplementedError()

FYI, there is a python module that provide some feature to enhance your 
abstract classes: http://docs.python.org/library/abc.html. These are 
more advanced features, you may just ignore that module for now.

JM



More information about the Python-list mailing list