摘要:[反射] Reflectoin
方法1:
class_name = "MyClass" method_name = "MyMethod" obj = globals()[class_name]() getattr(obj, method_name)()
方法2:
eval("MyClass().MyMethod()")
補充:
模組載入( full_class_name :完整名稱 如 app.MyClass )
def load_class(full_class_name): cls = None if full_class_name in globals(): cls = globals()[full_class_name] else: if "." in full_class_name: import importlib module_name, cls_name = full_class_name.rsplit('.', 1) mod = importlib.import_module(module_name) #importlib 可在runtime 時動態載入 package cls = (getattr(mod, cls_name)) return cls