A fairly straight-forward translation should do it:
def template(baseclass):
class Foo(baseclass):
def fun(self):
print "%s::fun()" % self.__class__.__name__
# derive a class name for the subclass returned (optional)
Foo.__name__ = "_".join([Foo.__name__, baseclass.__name__])
return Foo
class Base1:
def bar(self):
print "Base1::bar()"
class Base2:
def bar(self):
print "Base2::bar()"
Foo_Base1 = template(Base1)
print 'Foo_Base1 base classes:', Foo_Base1.__bases__
Foo_Base2 = template(Base2)
print 'Foo_Base2 base classes:', Foo_Base2.__bases__
d1 = Foo_Base1()
d1.fun()
d1.bar()
d2 = Foo_Base2()
d2.fun()
d2.bar()
# Ouput:
# Foo_Base1 base classes: (<class __main__.Base1 at 0x00A56C70>,)
# Foo_Base2 base classes: (<class __main__.Base2 at 0x00ABFA78>,)
# Foo_Base1::fun()
# Base1::bar()
# Foo_Base2::fun()
# Base2::bar()
# Foo_Base2::fun()
# Base2::bar()
Explanation: In the code the (poorly-named) template()
function is an example of what is commonly called a "class factory". For more information (warning: shameless plug) see my answer to the question "What exactly is a Class Factory?" on this site.
Edit: Added code to create different class name for each subclass returned (inspired by @AaronMcSmooth's answer with insightful comment about potential confusion when debugging).