如何动态加载 Python 类 [英] How to dynamically load a Python class

查看:68
本文介绍了如何动态加载 Python 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 Python 类的字符串,例如my_package.my_module.MyClass,加载它的最佳方式是什么?

Given a string of a Python class, e.g. my_package.my_module.MyClass, what is the best possible way to load it?

换句话说,我正在寻找 Java 中的等效 Class.forName(),Python 中的函数.它需要在 Google App Engine 上运行.

In other words I am looking for a equivalent Class.forName() in Java, function in Python. It needs to work on Google App Engine.

最好是一个接受类的 FQN 作为字符串的函数,并返回对类的引用:

Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:

my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()

推荐答案

从 python 文档中,这里是你想要的函数:

From the python documentation, here's the function you want:

def my_import(name):
    components = name.split('.')
    mod = __import__(components[0])
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

简单的 __import__ 行不通的原因是,任何导入包字符串中第一个点之后的任何内容都是您正在导入的模块的属性.因此,这样的事情是行不通的:

The reason a simple __import__ won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work:

__import__('foo.bar.baz.qux')

你必须像这样调用上面的函数:

You'd have to call the above function like so:

my_import('foo.bar.baz.qux')

或者就您的示例而言:

klass = my_import('my_package.my_module.my_class')
some_object = klass()

EDIT:我对此有点偏离.您基本上想要做的是:

EDIT: I was a bit off on this. What you're basically wanting to do is this:

from my_package.my_module import my_class

仅当您有一个 fromlist 时,才需要上述功能.因此,适当的调用应该是这样的:

The above function is only necessary if you have a empty fromlist. Thus, the appropriate call would be like this:

mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')

这篇关于如何动态加载 Python 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆