Thursday, January 8, 2009

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

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

2 Using eval.
  1. eval('classname')  


3 Using new-style classes,make up a base class that has a classmethod, something like this:
  1. class Parent(object):  
  2.     @classmethod  
  3.     def getSubClass(cls,name):  
  4.         for c in cls.__subclasses__:  
  5.             if c.__name__ == name:  
  6.             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.
  1. getattr(module,classname)  

No comments: