views:

90

answers:

2

Hello Stack Overflow contributers,

I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories of directories, etc. etc.), but I'm having trouble with something: What is the actual difference between a metaclass and a parameterized class, according to the website's definition?

If you can, please include code examples in Python that illustrate the differences between the two. Thank you for your help!

A: 

This write up may be of help. And this one is an oldie but worth a read as well. I know that this doesn't fully answer your question but I hope it gives you food for thought.

Manoj Govindan
+5  A: 

Python doesn't have (or need) "parameterized classes", so it's hard to provide examples of them in Python;-). A metaclass is simply "the class of a class": normally type (as long, in Py2, as you remember to make the class new-style by inheriting from object, or some other built-in type or other new-style class -- old-style classes are a legacy artefact in Py2, fortunately disappeared in Py3, and you should ideally just forget about them). You can make a custom metaclass (usually subclassing type) for several advanced purposes, but it's unlikely that you'll ever need to (esp. considering that, since python 2.6, much of what used to require a custom metaclass can now be done more simply with a class decorator).

Given any class C, type(C) is its metaclass.

A parameterized class is a completely different concept. Closest you can come to it in Python is probably a factory function that makes and returns a class based on its arguments:

def silly(n):
    class Silly(object):
        buh = ' '.join(n * ['hello])
    return Silly

Silly1 = silly(1)
Silly2 = silly(2)
a = Silly1()
print(a.buh)
b = Silly2()
print(b.buh)

will print

'hello'
'hello hello'

Again, it's definitely not something you'll need often -- making several classes that differ just by one or a few arguments. Anyway, as you can see, it has absolutely nothing to do with the classes' class (AKA metaclass), which is always type in this example (and in almost every more realistic example I could think of -- I just chose to give a simple example, where the point of doing this is hard to discern, rather than a realistic and therefore necessarily very complex one;-).

Alex Martelli
I switched to Py3 a couple of days ago, thinking that since I'm just a student right now, I should learn the 'hip new thing' of tomorrow. Guess that was a smart move :-)
yrsnkd
+1. Good explanation.
Manoj Govindan
+1 Excellent explanation as always.
katrielalex