动态实例化python类的对象类似于PHP new $ classname?

时间:2013-05-22 15:48:26

标签: python reflection

如果一个类的名称作为字符串变量给出(即动态实例化该类的对象),如何实例化该类。或者,以下PHP 5.3+代码如何

<?php

namespace Foo;

class Bar {};

$classname = 'Foo\Bar';
$bar = new $classname();

可以用python拼写吗?

另见

Does python have an equivalent to Java Class.forName()?

2 个答案:

答案 0 :(得分:1)

foo.py

class Bar(object):
    pass

test.py

from importlib import import_module

module = import_module('foo')
BarCls = getattr(module, 'Bar')
bar = BarCls()

答案 1 :(得分:1)

以下是我用来从完整类路径(例如foo.bar.baz.TheClass)到类本身的一些代码:

def get_class(class_path):
    module_path, class_name = class_path.rsplit(".", 1)

    try:
        module = __import__(module_path, fromlist=[class_name])
    except ImportError:
        raise ValueError("Module '%s' could not be imported" % (module_path,))

    try:
        cls = getattr(module, class_name)
    except AttributeError:
        raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))

    return cls

用法:

>>> get_class('twisted.internet.nonexistant.Deferred')

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    get_class('twisted.internet.nonexistant.Deferred')
  File "<pyshell#1>", line 7, in get_class
    raise ValueError("Module '%s' could not be imported" % (module_path,))
ValueError: Module 'twisted.internet.nonexistant' could not be imported
>>> get_class('twisted.internet.defer.NoClass')

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    get_class('twisted.internet.defer.NoClass')
  File "<pyshell#13>", line 12, in get_class
    raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))
ValueError: Module 'twisted.internet.defer' has no class 'NoClass'
>>> get_class('twisted.internet.defer.Deferred')
<class twisted.internet.defer.Deferred at 0x02B25DE0>

请注意,这不一定返回一个类,它只返回导入模块的属性:

>>> get_class('twisted.internet')
<module 'twisted.internet' from 'C:\Python26\lib\site-packages\twisted\internet\__init__.pyc'>