Home  >  Article  >  Backend Development  >  动态创建类实例代码

动态创建类实例代码

WBOY
WBOYOriginal
2016-06-06 11:26:44970browse

例如:
import mymodule
myobject = mymodule.myclass()
或者
from mymodule import myclass
myobject = myclass()

如果要在程序中动态地创建类实例,也一样要分两步走,例如:
m = __import__('mymodule')
c = getattr(m, 'myclass')
myobject = c()

但是要注意:如果myclass并不在mymodule的自动导出列表中(__all__),则必须显式地导入,例如:
m = __import__('mymodule', globals(), locals(), ['myclass'])
c = getattr(m, 'myclass')
myobject = c()

若要封装的规范一些,可以这样来做:
Code

代码如下:


class Activator:
'''本类用来动态创建类的实例'''
@staticmethod
def createInstance(class_name, *args, **kwargs):
'''动态创建类的实例。
[Parameter]
class_name - 类的全名(包括模块名)
*args - 类构造器所需要的参数(list)
*kwargs - 类构造器所需要的参数(dict)
[Return]
动态创建的类的实例
[Example]
class_name = 'knightmade.logging.Logger'
logger = Activator.createInstance(class_name, 'logname')
'''
(module_name, class_name) = class_name.rsplit('.', 1)
module_meta = __import__(module_name, globals(), locals(), [class_name])
class_meta = getattr(module_meta, class_name)
object = class_meta(*args, **kwargs)
return object

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn