簡體   English   中英

動態實例化python類的對象類似於PHP new $ classname?

[英]Dynamically instantiate object of the python class similar to PHP new $classname?

如果一個類的名稱作為字符串變量給出(即動態實例化該類的對象),如何實例化該類。 或者,以下PHP 5.3+代碼如何

<?php

namespace Foo;

class Bar {};

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

可以拼寫python?

另見

python是否具有Java Class.forName()的等價物?

foo.py

class Bar(object):
    pass

test.py

from importlib import import_module

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

下面是我用來從完整類路徑(例如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'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM