Python: Class factory using user input as class names

Posted by Sano98 on Stack Overflow See other posts from Stack Overflow or by Sano98
Published on 2010-03-17T11:20:31Z Indexed on 2010/03/17 11:21 UTC
Read the original article Hit count: 444

Hi everyone,

I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input.

There is a superclass "Unit", to which I can add attributes at runtime. This already works.

def add_attr (cls, name, value):
    setattr(cls, name, value)

class Unit(object):
    pass

class Archer(Unit):
    pass

myArcher = Archer()
add_attr(Unit, 'strength', 5)
print "Strenght ofmyarcher: " + str(myArcher.strength)
Archer.strength = 2
print "Strenght ofmyarcher: " + str(myArcher.strength)

This leads to the desired output:
Strenght ofmyarcher: 5
Strenght ofmyarcher: 2

But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this:

class Meta(type, subclassname):
    def __new__(cls, subclassname, bases, dct):
    return type.__new__(cls, subclassname, Unit, dct)

factory = Meta()    
factory.__new__("Soldier")  

but no luck. I guess I haven't really understood what new does here. What I want as a result here is

class Soldier(Unit):
    pass

being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created.

Any ideas? Many thanks in advance!
Bye
-Sano

© Stack Overflow or respective owner

Related posts about python

Related posts about metaclass