Metaclass vs Class factory

L

lbolognini

Hi all,

I dare risk my brain exploding by reaching for the understanding of
metaclasses.

At first i thought i almost got them, even if vaguely back in a corner
of my mind, my understanding was that, as classes' class a metaclass
would be able to return a different class based on input...

.... until i thought of factory functions and, Python considering
classes just another first-class object, as such i started considering
them.

So is anybody experienced in the dark side semantics of Python willing
to explain the difference, in simple terms, between a metaclass and a
function that returns a class?

Thanks,
Lorenzo
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
Hi all,

I dare risk my brain exploding by reaching for the understanding of
metaclasses.

At first i thought i almost got them, even if vaguely back in a corner
of my mind, my understanding was that, as classes' class a metaclass
would be able to return a different class based on input...

... until i thought of factory functions and, Python considering
classes just another first-class object, as such i started considering
them.

So is anybody experienced in the dark side semantics of Python willing
to explain the difference, in simple terms, between a metaclass and a
function that returns a class?

The same as the difference between a class and a function that returns
an instance.

One of the main use of metaclasses it to allow "postprocessing" of the
class object - ie, to automatically add extra features to a class,
usually based on the class definition. This is mostly useful for
framework stuff, where it can avoids quite a lot of boilerplate. IOW,
the 'input' of a metaclass is often the class object itself. The
metaclass constructor (I mean the proper constructor, __new__) let you
play with the class bases and attributes before the class object is
instanciated, and the initializer (__init__) let you modify the class
object after instanciation.

You can of course use the metaclass constructor as a class factory
(which it is), but it's obviously overkill if all you need is to
dynamically 'select' a class based on either inputs and/or environment
(configuration, platform, whatnot).

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,088
Latest member
JeremyMedl

Latest Threads

Top