คุณต้องการที่ชั้นซึ่งอาศัยอยู่ในโมดูลBaz foo.barด้วย Python 2.7 คุณต้องการใช้importlib.import_module()เนื่องจากจะทำให้การเปลี่ยนเป็น Python 3 ง่ายขึ้น:
import importlib
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
ด้วย Python <2.7:
def class_for_name(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = __import__(module_name, globals(), locals(), class_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c
ใช้:
loaded_class = class_for_name('foo.bar', 'Baz')