Can a class instance also be a class?

Steve Holden sholden at holdenweb.com
Thu Aug 15 06:22:20 EDT 2002


"Blair Hall" <b.hall at irl.cri.nz> wrote ...
> I'm betting that the answer is no, but if I am wrong please explain!
>
> The background to my question is that I was wondering about the most
> appropriate ways of writing classes that are parameterized (like C++
> templates).
>
>
> My first choice was to wrap a class definition in a function, like
>
> def _T_aClass(some_T):
>     class _aClass(object):
>         # ... uses some_T  for something in body
>
>     return _aClass
>
> This solution seems ok.
>
> I wondered if a class could do something similar.
> My first attempt doesn't look good but perhaps there
> are improvements possible?
>
> class _T_aClass(object):
>
>     def __init__(self,some_T):
>         class _aClass(object):
>             # ... uses some_T  for something in body
>         self.__theClass
>
>     def __call__(self):
>         return self.__theClass
>
> If nothing else, I don't like the fact that an instance of _T_aClass is
> an object which when called
> like a function returns a class.
>
Nothing wrong with that. You just need to loosen up a little! ;-)

Python's "classic" classes have instances, which didn't buy you that much.
They are essentially a fixed object type, with a fixed behaviour (including
the fact that if you call them they return an instance). Your current
approach is sound, but can be extended from Python 2.2 onwards.

The "new-style" classes are subclasses of built-in types (I usually think of
them as subtypes, and reserve the term "class" for user-defined classes, but
my approach to terminology has always been sloppy). These types are
themselves instances of type TypeType. Consequently you can subclass the
type type (in pretty much the same way you subclass classic classes) to give
you a specialized type, which behaves in a different way from the curent
built in types.

This can lead to severe headaches and a sudden wish to visit the pub. For
further information see

    http://www.python.org/2.2/descrintro.html#metaclasses

This will either radically change your approach, or convince you that you
are doing fine as you are.

in-which-case-mine's-a-pint-ly y'rs  - steve
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list