简体   繁体   English

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

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

How to instantiated a class if its name is given as a string variable (ie dynamically instantiate object of the class). 如果一个类的名称作为字符串变量给出(即动态实例化该类的对象),如何实例化该类。 Or alternatively, how does the following PHP 5.3+ code 或者,以下PHP 5.3+代码如何

<?php

namespace Foo;

class Bar {};

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

can be spelled in python? 可以拼写python?

Also see 另见

Does python have an equivalent to Java Class.forName()? python是否具有Java Class.forName()的等价物?

foo.py foo.py

class Bar(object):
    pass

test.py test.py

from importlib import import_module

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

Here is some code I use to go from a full class path (eg foo.bar.baz.TheClass ) to the class itself: 下面是我用来从完整类路径(例如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

Usage: 用法:

>>> 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>

Note that this doesn't necessarily return a class, it just returns the attribute of the imported module: 注意,这不一定返回一个类,它只返回导入模块的属性:

>>> 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.

相关问题 如何在python中动态实例化类? - How to instantiate class in python dynamically? 如何在新的 class 中实例化 object? - How to instantiate an object in a new class? 在python中将类实例化为可调用对象 - instantiate class in python as a callable object 在这个例子中,如何动态实例化(通过classname作为字符串)类来调用getThings()? - How can I dynamically instantiate (by classname as a string) the class to call getThings() in this example? 类classname:AND class classname()之间的区别:AND class classname(object): - Difference between class classname: AND class classname(): AND class classname(object): class Classname(object),Python中的object是什么词? - class Classname(object), what sort of word is 'object' in Python? 使用 locate 动态实例化类 - Instantiate class dynamically with locate Python 3.9 如果一个字符串匹配一个class的名字,实例化class(动态实例化具体的class) - Python 3.9 if a string matches a class name, instantiate the class (instantiate a specific class dynamically) 在Python中动态实例化类 - dynamically instantiate classes in Python 如何动态地知道和实例化在 Python 模块中实现的一个 class - How to know and instantiate only one class implemented in a Python module dynamically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM