从字符串中获取python类对象

从字符串中获取python类对象,python,Python,可能重复: 可能是个简单的问题!我需要遍历从设置文件传递的类列表(作为字符串)。课程如下所示: TWO_FACTOR_BACKENDS = ( 'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication 'id.backends.TOTPBackend', 'id.backends.HOTPBackend', #'id.backends.YubikeyB

可能重复:

可能是个简单的问题!我需要遍历从设置文件传递的类列表(作为字符串)。课程如下所示:

TWO_FACTOR_BACKENDS = (
    'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
    'id.backends.TOTPBackend',
    'id.backends.HOTPBackend',
    #'id.backends.YubikeyBackend',
    #'id.backends.OneTimePadBackend',
    #'id.backends.EmailBackend',
)
我现在需要对这些类中的每一个调用
authenticate()
函数(当然,除非注释掉)。我正在愉快地遍历列表,我只需要知道如何将字符串转换为foreach循环中的Class对象,以便调用它的
authenticate
方法。有没有一种简单的方法可以做到这一点?

您想使用它来处理这样的模块加载,然后只需使用它来获取类

例如,假设我有一个模块,
somemodule.py
,其中包含类
Test

import importlib

cls = "somemodule.Test"
module_name, class_name = cls.split(".")

somemodule = importlib.import_module(module_name)

print(getattr(somemodule, class_name))
给我:

<class 'somemodule.Test'>
如果模块/包已经导入,它将不会导入,因此您可以愉快地执行此操作,而无需跟踪加载模块:

import importlib

TWO_FACTOR_BACKENDS = (
    'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
    'id.backends.TOTPBackend',
    'id.backends.HOTPBackend',
    #'id.backends.YubikeyBackend',
    #'id.backends.OneTimePadBackend',
    #'id.backends.EmailBackend',
)

backends = [getattr(importlib.import_module(mod), cls) for (mod, cls) in (backend.rsplit(".", 1) for backend in TWO_FACTOR_BACKENDS)]

您希望对类或这些类的对象调用
authenticate()
?抱歉,对类而不是类的对象调用
authenticate()
。应该说得更清楚对不起!
import importlib

TWO_FACTOR_BACKENDS = (
    'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
    'id.backends.TOTPBackend',
    'id.backends.HOTPBackend',
    #'id.backends.YubikeyBackend',
    #'id.backends.OneTimePadBackend',
    #'id.backends.EmailBackend',
)

backends = [getattr(importlib.import_module(mod), cls) for (mod, cls) in (backend.rsplit(".", 1) for backend in TWO_FACTOR_BACKENDS)]