【发布时间】:2020-07-24 02:44:50
【问题描述】:
假设我有myfile.py 和一些类A、B 和C 在里面定义。现在我想通过它在 str 中的名称来实例化类。我不明白要传递给getattr 什么才能做到这一点。所有examples like this 都假定类在其他模块中:
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
但我没有module_name。
【问题讨论】:
-
不认为这是好的做法,但是
x = globals()['Foo']()
标签: python python-3.x reflection