我需要接受一个字符串参数,并在Python中创建在该字符串中命名的类的对象。在Java语言中,我会使用Class.forName().newInstance()
。在Python中有没有等价物?
感谢您的回复。为了回答那些想知道我在做什么的人:我想使用命令行参数作为类名,并实例化它。我实际上是在用Jython编程并实例化Java类,这就是问题的Java性质。getattr()
运行得很好。非常感谢。
发布于 2009-01-17 08:13:06
假设类在您的作用域中:
globals()['classname'](args, to, constructor)
否则:
getattr(someModule, 'classname')(args, to, constructor)
编辑:注意,你不能给getattr起一个像'foo.bar‘这样的名字。你需要把它拆分。并从左到右对每个块调用getattr()。这将会处理这个问题:
module, rest = 'foo.bar.baz'.split('.', 1)
fooBar = reduce(lambda a, b: getattr(a, b), rest.split('.'), globals()[module])
someVar = fooBar(args, to, constructor)
发布于 2015-05-05 09:00:38
def import_class_from_string(path):
from importlib import import_module
module_path, _, class_name = path.rpartition('.')
mod = import_module(module_path)
klass = getattr(mod, class_name)
return klass
用法
In [59]: raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')()
---------------------------------------------------------------------------
DeadlineExceededError Traceback (most recent call last)
<ipython-input-59-b4e59d809b2f> in <module>()
----> 1 raise import_class_from_string('google.appengine.runtime.apiproxy_errors.DeadlineExceededError')()
DeadlineExceededError:
发布于 2010-08-31 22:41:59
还有另一种实现。
def import_class(class_string):
"""Returns class object specified by a string.
Args:
class_string: The string representing a class.
Raises:
ValueError if module part of the class is not specified.
"""
module_name, _, class_name = class_string.rpartition('.')
if module_name == '':
raise ValueError('Class name must contain module part.')
return getattr(
__import__(module_name, globals(), locals(), [class_name], -1),
class_name)
https://stackoverflow.com/questions/452969
复制相似问题