Thursday, January 8, 2009

How to get the reference of a global class by name in Python

1 Useing Globals().
Globals()['classname']

2 Using eval.
eval('classname')


3 Using new-style classes,make up a base class that has a classmethod, something like this:
class Parent(object):
    @classmethod
    def getSubClass(cls,name):
        for c in cls.__subclasses__:
            if c.__name__ == name:
            return c

Everything classes inherits this one, which will enable it possible to dynamically get the references of the sub-classes.

4 Using getattr(), if the module that the the class lives in is known.
getattr(module,classname)

No comments: