python通过字符串获取类对象


python通过字符串获取类对象:

globals()‘classname’ # 只是当前的local文件作用域

getattr(someModule, ‘classname’)(args, to, constructor)

eval() 不建议使用

can be used to execute arbitrary Python code. You should never use eval() with untrusted strings.

__import__

Say for example, if you class name is foo.baz.bar

m = __import__( "foo.baz.bar" ) #m is package foo
m = getattr( m, "baz" ) #m is package baz
m = getattr( m, "bar" ) #m is module bar
m = getattr( m, "Model" ) #m is class Model

importlib

importlib.import_module('accounting.views') 

sys.modules

import sys
import types

def str_to_class(field):
    try:
        identifier = getattr(sys.modules[__name__], field)
    except AttributeError:
        raise NameError("%s doesn't exist." % field)
    if isinstance(identifier, (types.ClassType, types.TypeType)):
        return identifier
    raise TypeError("%s is not a class." % field)
Buy me a 肥仔水!