I’ve read some tutorials on Python metaclasses. I’ve never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Since I got the idea from C++/D templates, here’s an example of what the code I want to write would look like in C++:
template<class T>
class Foo : T {
void fun() {}
}
Although it certainly can be done with metaclasses, you can do what you want without them because in Python classes are themselves objects. The means that—surprisingly—essentially nothing more than an almost one-to-one translation of the C++ code is required. Besides being relatively uncomplicated because of this, it’ll also work without modification in both Python 2 & 3.
Output:
The code in the (unimaginatively-named)
template()function is an example of what is commonly called a class factory or an implementation of the Factory pattern. So, incidentally, you might find my answer to the question What exactly is a Class Factory? informative.Edit: Added code to create different class names for each subclass returned—which was inspired by @aaronasterling‘s insight (in a now deleted comment) about potential confusion when debugging if the class manufactured always has the same name.